JMon
JMon

Reputation: 3447

get new inserted ID in MVC Controller to jQuery

I am updating an entity normally inside a controller as follows :-

[HttpPost]
public ActionResult Create(Project project)
{
  //var model = new CompositeImageModel(0);
  if (ModelState.IsValid)
  {
    //var model = new CompositeImageModel(project.ProjectID);
    db.Projects.Add(project);
    db.SaveChanges();
    ViewBag.ProjectID = project.ProjectID;

    return RedirectToAction("Index");
  }

  return View();
}

And I wish to grab this new id "ViewBag.ProjectID" inside my Jquery AJAX code :-

onSaveBegin: function () {
  //CODE FOR SAVE BEGIN    
  $('#imageList').fadeIn('slow');
  $("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/222"); }); 

},

instead of the hardcoded "222".

How can I get it?

Thanks for your help and time

**********UPDATE**************************** So I have updated my Jquery as follows :-

<script type="text/javascript">
$(document).ready(function () {

    var imageList = $('#imageList'),
        submitButt = $('#submitButt');

    //hide the imageList initially
    imageList.hide(); //hide all but the first paragraph

    });


    var Project = {
        save: function () {
            var projectForm = $("#projectForm");
            if (projectForm.valid()) {
                projectForm.submit();
            }
            else {
                Project.onInvalidForm();
            }
        },
        onInvalidForm: function () {
            //CODE FOR INVALID FORM 
        },
        onSaveBegin: function () {
            //CODE FOR SAVE BEGIN    
            $('#imageList').fadeIn('slow');
        },
        onSaveSuccess: function () {
            //CODE FOR SAVE SUCCESS    
        },
        onSaveFailure: function () {
            //CODE FOR SAVE FAILURE    
            alert(ViewBag.ProjectID);
        },
        onSaveComplete: function () {
            //CODE FOR SAVE COMPLETE    
            //var hfProjectId = $("#hfProjectId").val();
            //$("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/" + hfProjectId); });
            $("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/"+@(ViewBag.ProjectID) ); }); 
        }
    }; 

I have moved the code to onSaveComplete, since I should have the ProjectID then, but still am not able to get it yet. however both options will not work.

**********UPDATE 2 ***************************

@model MvcCommons.Models.Project

@{
ViewBag.Title = "Create";

}

<h2>Create</h2>

@{    
Layout = "~/Views/Shared/_Layout.cshtml";    
Html.EnableClientValidation();    
Html.EnableUnobtrusiveJavaScript(); 

}

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript">
        $(document).ready(function () {

    var imageList = $('#imageList'),
        submitButt = $('#submitButt');

        //hide the imageList initially
    imageList.hide(); //hide all but the first paragraph

    });


    var Project = {
        save: function () {
            var projectForm = $("#projectForm");
            if (projectForm.valid()) {
                projectForm.submit();
            }
            else {
                Project.onInvalidForm();
            }
        },
        onInvalidForm: function () {
            //CODE FOR INVALID FORM 
        },
        onSaveBegin: function () {
            //CODE FOR SAVE BEGIN    
            $('#imageList').fadeIn('slow');
        },
        onSaveSuccess: function () {
            //CODE FOR SAVE SUCCESS    
        },
        onSaveFailure: function () {
            //CODE FOR SAVE FAILURE    
            alert(ViewBag.ProjectID);
        },
        onSaveComplete: function () {
            //CODE FOR SAVE COMPLETE    
            //var hfProjectId = $("#hfProjectId").val();
            //$("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/" + hfProjectId); });

            $("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/"+@(ViewBag.ProjectID) ); }); 
        }
    }; 

@{ var projectID = int.Parse(ViewBag.ProjectID);
}

@using (Ajax.BeginForm(
"/Create",
new { },
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "projectFormContainer",
OnComplete = "Project.onSaveComplete",
OnFailure = "Project.onSaveFailure", OnSuccess = "Project.onSaveSuccess", OnBegin = "Project.onSaveBegin"
},
new { id = "projectForm", name = "projectForm" }))
{

         @Html.Hidden("hfProjectId", ViewBag.ProjectID)

        <div class="editor-label">          
            @Html.LabelFor(m => m.ProjectTitle)       
         </div>       
         <div class="editor-field">          
            @Html.TextBoxFor(m => m.ProjectTitle)          
            @Html.ValidationMessageFor(m => m.ProjectTitle)       
         </div>       
         <div class="editor-label">          
            @Html.LabelFor(m => m.ProjectText)       
         </div>       
         <div class="editor-field">          
            @Html.TextBoxFor(m => m.ProjectText)          
            @Html.ValidationMessageFor(m => m.ProjectText)       
         </div>       
         <p>       
            <input type="submit" value="Submit" onclick="Project.save();" />       
         </p>    
      </div>    
}


<div id='imageList'>
    <h2>Upload Image(s)</h2>
    @{ 
        Html.RenderPartial("~/Views/File/ImageUpload.cshtml", new MvcCommons.ViewModels.ImageModel((int)ViewBag.ProjectID));
     }
</div>
@Html.ActionLink("Back to List", "Index")

Code updated with latest changes

***********UPDATED*************************

Mode updates :- Change the @Html.Hidden to this now :-

            @if(Model != null)
        {
             @Html.Hidden("hfProjectId", Model.ProjectID)
        }

The Javascript is still the same :=

            onSaveComplete: function () {
            //CODE FOR SAVE COMPLETE    
            var hfProjectId = $("#hfProjectId").val();
            alert(hfProjectId);
            $("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/" + hfProjectId); });
            //$("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/"+@(ViewBag.ProjectID) ); }); 
        }

change the var projectID

@{
if (Model != null)  
{
    var projectID = Model.ProjectID;
}

}

in the controller, returning a "View", with the model

        [HttpPost]
    public ActionResult Create(Project project)
    {
        if (ModelState.IsValid)
        {
            db.Projects.Add(project);
            db.SaveChanges();
            ViewBag.ProjectID = project.ProjectID;
            //return RedirectToAction("Index");
            return View("Create", project);
        }

        return View();
    }

Still no luck though!

********** FINAL UPDATE **************************** I have decided to create a Project View Model and try to pass variables through it, since the ViewBag was not working in my case. So I changed the HttpPost Create function in the Controller to look as follows :-

        [HttpPost]
    public ActionResult Create(Project project)
    {
        ProjectModel viewModel = new ProjectModel();

        if (ModelState.IsValid)
        {
            db.Projects.Add(project);
            db.SaveChanges();
            viewModel.Project = project;
            return View("Index", viewModel);
        }

        return View();
    }

However this still did not refresh the ProjectID, and so I have decided to abandon this for the time being and try to come up with a better design. However if you could see soemthign wrong that I am doing please comment on this.

This is my final Create View :-

@model MvcCommons.ViewModels.ProjectModel
@{
var projectID = Model.Project.ProjectID;

}

@{ ViewBag.Title = "Create"; }

Create

@{    
Layout = "~/Views/Shared/_Layout.cshtml";    
Html.EnableClientValidation();    
Html.EnableUnobtrusiveJavaScript(); 

}

`

` $(document).ready(function () {

    var imageList = $('#imageList'),
        submitButt = $('#submitButt');

    //hide the imageList initially
    imageList.hide(); //hide all but the first paragraph

    });

    var Project = {
        save: function () {
            var projectForm = $("#projectForm");
            if (projectForm.valid()) {
                projectForm.submit();
            }
            else {
                Project.onInvalidForm();
            }
        },
        onInvalidForm: function () {
            //CODE FOR INVALID FORM 
        },
        onSaveBegin: function () {
            //CODE FOR SAVE BEGIN    
            alert('onSaveBegin ' + @(projectID));
            $('#imageList').fadeIn('slow');
        },
        onSaveSuccess: function () {
            //CODE FOR SAVE SUCCESS    
            //alert('onSaveSuccess')
        },
        onSaveFailure: function () {
            //CODE FOR SAVE FAILURE    
            //alert('onSaveFailure ' + @(projectID));
        },
        onSaveComplete: function () {
            //CODE FOR SAVE COMPLETE    
            //alert('onSaveComplete ' + @(projectID))
            //$("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/"+@(projectID)); });
            $("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/" + hfProjectId); });
        }
    }; 

@using (Ajax.BeginForm(    
"/Create",    
new { },    
new AjaxOptions    
{       
    InsertionMode = InsertionMode.Replace,       
    UpdateTargetId = "projectFormContainer",       
    OnComplete = "Project.onSaveComplete",       
    OnFailure = "Project.onSaveFailure",
    OnSuccess = "Project.onSaveSuccess",
    OnBegin = "Project.onSaveBegin"    
},    
new { id = "projectForm", name = "projectForm" }))    
{    
    <div>       

        @*@Html.Hidden("hfProjectId", projectID)*@ 
        @Html.Hidden("hfProjectId", Model.Project.ProjectID) 

        <div class="editor-label">          
            @Html.LabelFor(m => m.Project.ProjectTitle)       
         </div>       
         <div class="editor-field">          
            @Html.TextBoxFor(m => m.Project.ProjectTitle)          
            @Html.ValidationMessageFor(m => m.Project.ProjectTitle)       
         </div>       
         <div class="editor-label">          
            @Html.LabelFor(m => m.Project.ProjectText)       
         </div>       
         <div class="editor-field">          
            @Html.TextBoxFor(m => m.Project.ProjectText)          
            @Html.ValidationMessageFor(m => m.Project.ProjectText)       
         </div>       
         <p>       

@* *@



}

<div id='imageList'>
    <h2>Upload Image(s)</h2>
    @{ 
        //Html.RenderPartial("~/Views/File/ImageUpload.cshtml", new MvcCommons.ViewModels.ImageModel((int)ViewBag.ProjectID));
        Html.RenderPartial("~/Views/File/ImageUpload.cshtml", new MvcCommons.ViewModels.ImageModel(projectID));
     }
</div>
@Html.ActionLink("Back to List", "Index")

Upvotes: 1

Views: 2242

Answers (1)

Mohammed Swillam
Mohammed Swillam

Reputation: 9242

Easy way (Not very sure about it)

$("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/"+@(ViewBag.ProjectID) ); }); 

The Normal way

1- Put a HiddenField inside your view

2- Get the value from ViewBag.ProjectID and assign it to this hidden field

3- Read it with jQuery and then use it wherever you want.

an Example should eb added to this answer right away.

Example:

Update

//  Get the projectID value
    var projectID = int.parse(ViewBag.ProjectID);

// add a hiddenfield and set it's value to the projectID
@Html.Hidden("hfProjectId", projectID)

// inside your jQuery code, get the hiddenField value
var hfProjectId = $("#hfProjectId").val();

// use this value inside your code
$("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/"+hfProjectId ); }); 

Upvotes: 1

Related Questions