如何通过Url.Action传递Model?

时间:2022-03-18 15:16:19

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?

我想在Jquery Dailog中返回一个局部视图,并希望将viewmodel对象传递给特定的控制器动作,该怎么做?

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?

目前,“homeViewModel.SelectedCountry”是Null,如何在Jquery中传递模型?

2 个解决方案

#1


3  

You convert the model into an JSON object by using the the build-in JSON-helper, just modify your request to:

您可以使用内置的JSON帮助程序将模型转换为JSON对象,只需将您的请求修改为:

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

@Html.Raw is needed to prevent HTML-Encoding.

需要@ Html.Raw来防止HTML编码。

I tested it and it worked.

我测试了它,它工作。

#2


4  

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

如果您使用的是AJAX,则不应使用HTTP GET将模型传递给服务器。而是使用HTTP POST(如$()。ajax({method:'POST'})并将数据作为POST数据传递($()。ajax({method:'POST',data:@ Html.Raw(Json。编码(型号))}))

#1


3  

You convert the model into an JSON object by using the the build-in JSON-helper, just modify your request to:

您可以使用内置的JSON帮助程序将模型转换为JSON对象,只需将您的请求修改为:

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

@Html.Raw is needed to prevent HTML-Encoding.

需要@ Html.Raw来防止HTML编码。

I tested it and it worked.

我测试了它,它工作。

#2


4  

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

如果您使用的是AJAX,则不应使用HTTP GET将模型传递给服务器。而是使用HTTP POST(如$()。ajax({method:'POST'})并将数据作为POST数据传递($()。ajax({method:'POST',data:@ Html.Raw(Json。编码(型号))}))