I want to return a partial view in Jquery Dailog and wanted to pass the viewmodel object to particular controller action, how to do that?
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 to pass model in Jquery?
You can use TempData to pass the object.
By including a NuGet package called MvcContrib you can easily pass model or form data through a simple RedirectToAction function call inside of your controllers.
You can pass them via a URL, a query string, a request header, a request body, or even a form.
If you're using AJAX, you should not use HTTP GET to pass model to server. Instead use HTTP POST (as in $().ajax({method: 'POST'})
and pass data as POST data ($().ajax({method: 'POST', data: @Html.Raw(Json.Encode(Model))})
)
You convert the model into an JSON object by using the the build-in JSON-helper, just modify your request to:
$(this).load('@Url.Action("CreatePartial")',@Html.Raw(Json.Encode(Model)));
@Html.Raw is needed to prevent HTML-Encoding.
I tested it and it worked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With