How to pass a model using Url.Action?

I want to return a partial view to JQuery Dailog and wanted to pass the viewmodel object to a specific controller action, how to do this?

View

@Html.DropDownListFor(model => model.SelectedCountry, new SelectList(Model.CountryList, "CountryCode", "CountryName"), "---SELECT COUNTRY---", new { @class = "chosen", @onchange = "this.form.action='/Home/Index'; this.form.submit(); " }) <input type="button" id="button1" value="Push"/> <div id="dialog" title="Report" style="overflow: hidden;"></div> 

Js

 <script type="text/javascript"> $(function () { $('#dialog').dialog({ autoOpen: false, width: 400, resizable: false, title: 'Report', modal: true, open: function() { //here how to pass viewmodel $(this).load("@Url.Action("CreatePartial")"); }, buttons: { "Close": function () { $(this).dialog("close"); } } }); $('#button1').click(function () { $('#dialog').dialog('open'); }); }); 

controller

 public ActionResult CreatePartial(HomeViewModel homeViewModel) { return PartialView("_CreatePartial", homeViewModel); } 

Currently, "homeViewModel.SelectedCountry" is Null, how do I pass a model to jQuery?

+6
source share
2 answers

You convert the model into a JSON object using the built-in JSON helper, just change your request to:

 $(this).load('@Url.Action("CreatePartial")',@Html.Raw(Json.Encode(Model))); 

@ Html.Raw is necessary to prevent HTML coding.

I tested it and it worked.

+3
source

If you use AJAX, you should not use HTTP GET to transfer the model to the server. Instead, use HTTP POST (as in $().ajax({method: 'POST'}) and pass the data as POST data ( $().ajax({method: 'POST', data: @Html.Raw(Json.Encode(Model))}) )

+4
source

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


All Articles