asp.net-mvc 如何通过 Url.Action 传递模型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12237684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:13:45  来源:igfitidea点击:

how to pass Model with Url.Action?

asp.net-mvc

提问by user584018

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

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 中传递模型?

采纳答案by developer10214

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

您可以使用内置的 JSON-helper 将模型转换为 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.

我测试了它并且它起作用了。

回答by Serg Rogovtsev

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(如 in$().ajax({method: 'POST'})并将数据作为 POST 数据 ( $().ajax({method: 'POST', data: @Html.Raw(Json.Encode(Model))}))