I have a main view and two partial views. I need to be able to populate the viewmodel with the values in my first partial view and pass the viewmodel to the second partial view on click of the button. The button is in the second partial view. I have written a javascript function to do that but the viewmodel is empty when I check the controller method. As you you can see in the screenshot below the services box is the second partial view
First Partial view
Second Partial View
@model CC.GRP.MCRequest.ViewModels.NewRequestViewModel <div id="NewRequest"> <h1>Services</h1> @using (Html.BeginForm()) { @Html.LabelFor(model => model.ProjectName, htmlAttributes: new { @class = "control-label col-md-5" }) @Html.EditorFor(model => model.ProjectName, new { htmlAttributes = new { @class = "form-control", style = "width:100%" } }) <input type="submit" value="Save" class="btn btn-default" onclick="mapInit()" /> } </div> <script type="text/javascript"> function mapInit() { $.ajax({ url: '@Url.Action("Service", "request")', // datatype: "json", data: $('form').serialize(), // update this type: "POST", // contentType: 'application/json; charset=utf-8' }); } </script>
Controller
[HttpPost] public PartialViewResult Service(NewRequestViewModel model) { return PartialView("_NewService", model); }
2 Answers
Answers 1
Here is my suggestion to you how to resolve your task:
- You have to change the type of your button on the Second partial view form to the button type:
<input type="button" value="Save" class="btn btn-default" onclick="mapInit()" />
This step is necessary not to clean your form when an original submit-event works out after your ajax method. In your mapInit function you should add a property
success
and write a function there to update your Second partial form by hand this way:function mapInit() { $.ajax({ url: '@Url.Action("Service", "request")', // datatype: "json", data: $('form').serialize(), // update this type: "POST", success: function (data) { var html = $(data).find('form').html(); $('#NewRequest').find('form').html(html); } }); }
Thus, providing that your First partial form has the same fields, you'll be able to fill your second form with what you want.
Answers 2
1) Create a get or post action for your partial view.This will get your posted model as parameter and returns second partial view.
2) Modify the BeginForm field of partial view in UI and add OnSuccess event.(eg Handel OnSuccess)
3) Create Jquery method to get request on success and replace the first partial view content with second one in UI.(eg: $('#PartialView1Container').html(result);)
0 comments:
Post a Comment