Passing viewmodel between partial views of MVC5

I have a main view and two partial views. I need to be able to populate the viewmodel with values ​​in my first partial view and pass the viewmodel to the second partial view when the button is clicked. The button is in a second partial view. I wrote a javascript function for this, but the viewmodel is empty when I test the controller method. As you can see in the screenshot below the service window - this is the second partial view

First partial view

enter image description here

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); } 
+5
source share
2 answers

Here is my suggestion on how to solve your problem:

  • You must change the type of your button on the form of the second partial view to the button type: <input type="button" value="Save" class="btn btn-default" onclick="mapInit()" /> This step is necessary so that clear the form when the original submit event completes after your ajax method.
  • In your mapInit function, you must add the success property and write a function there to manually update your second partial form as follows:

     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, if your first partial form has the same fields, you can fill out your second form with whatever you want.

0
source

1) Create a get or post action for your partial view. This will give you the published model as a parameter and return a second partial view.

2) Change the BeginForm partial view field in the user interface and add an OnSuccess event (for example, Handel OnSuccess )

3) Create a Jquery method to get a success request, and replace the first partial view content with the second in the user interface (for example: $ ('# PartialView1Container'). Html (result);)

0
source

Source: https://habr.com/ru/post/1266474/


All Articles