Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass Model with Url.Action?

Tags:

asp.net-mvc

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?

like image 950
user584018 Avatar asked Sep 02 '12 16:09

user584018


People also ask

How do you pass an object from one action to another action in MVC?

You can use TempData to pass the object.

Can we pass model in RedirectToAction?

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.

How can you pass an instance of a class to an action method?

You can pass them via a URL, a query string, a request header, a request body, or even a form.


2 Answers

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))}))

like image 69
Serg Rogovtsev Avatar answered Nov 15 '22 07:11

Serg Rogovtsev


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.

like image 42
developer10214 Avatar answered Nov 15 '22 07:11

developer10214