user584018
user584018

Reputation: 11304

how to pass Model with Url.Action?

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?

Upvotes: 6

Views: 35875

Answers (2)

Sergei Rogovtcev
Sergei Rogovtcev

Reputation: 5832

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

Upvotes: 4

developer10214
developer10214

Reputation: 1186

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.

Upvotes: 3

Related Questions