关于asp.net MVC:如何通过Url.Action传递模型?

how to pass Model with Url.Action?

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

视图

1
2
3
@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"/>

s

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<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');
    });
});

控制者

1
2
3
4
public ActionResult CreatePartial(HomeViewModel homeViewModel)
{
        return PartialView("_CreatePartial", homeViewModel);
}

当前," homeViewModel.SelectedCountry"为Null,如何在Jquery中传递模型?


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


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

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

@ Html.Raw是必需的,以防止HTML编码。

我对其进行了测试,并且效果良好。