jQuery 如何正确使用 Html.Raw(Json.Encode(Model))?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28701164/
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-08-26 16:30:50  来源:igfitidea点击:

How to use Html.Raw(Json.Encode(Model)) properly?

jqueryajaxjsonasp.net-mvcasp.net-ajax

提问by Dayan

I'm trying to Encode my MVC Model with the following code but the alert message gives me a null value. I'm not sure why it's giving me a null value because this is a create form. I'm trying to create a model from this and my html Code has the following look:

我正在尝试使用以下代码对我的 MVC 模型进行编码,但警报消息给了我一个空值。我不确定为什么它给我一个空值,因为这是一个创建表单。我正在尝试从中创建一个模型,我的 html 代码具有以下外观:

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Customer</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" id="submit" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    <script type="text/javascript">
        $(document).ready(function () {
            $('#submit').click(function () {
                var JsonModel = '@Html.Raw(Json.Encode(@Model))';

                alert(JsonModel); // json as string

                var model = JSON.parse(JsonModel); // will give json
                alert(model);

                $.ajax({
                    type: "POST",
                    url: "../Home/Index",
                    data: {"cus" :  model},
                    success: function(data){
                        alert("done");
                    },
                    error:function(){
                        alert("Error!!!!");
                    }
                });
            });
        });
    </script>
} 

采纳答案by Inspector Squirrel

My answer hereshows (in the JQuery section) how you can get around using Json.Encodealtogether.

在这里的回答显示(在 JQuery 部分)你可以如何Json.Encode完全使用。

The basic idea behind it is that by using a jQuery function you can build a JSON object, one that MVC will be able to parse into a data model, out of any form.

它背后的基本思想是,通过使用 jQuery 函数,您可以构建一个 JSON 对象,MVC 将能够将其解析为任何形式的数据模型。

The function is as follows:

功能如下:

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

In your case, your AJAX would become

在您的情况下,您的 AJAX 将成为

 $.ajax({
     type: "POST",
     url: "../Home/Index",
     data: { cus : JSON.stringify($('form').serializeObject()) },
     success: function(data){
         alert("done");
     },
     error:function(){
         alert("Error!!!!");
     }
 });

If you have trouble getting $('form')working, possibly if you have numerous forms on the same page, use classes or IDs to uniquely identify your forms.

如果您在$('form')工作时遇到问题,可能是同一页面上有多个表单,请使用类或 ID 来唯一标识您的表单。

回答by Chris Pratt

It's returning null because it isnull. The data that the user will eventually enter into the form is not available at the time the page is rendering (and your call to Json.Encode(Model)runs). Things like JavaScript run client-side, while all the Razor stuff runs server-sidebefore it's sent down to the client. If you want to get the user-entered data from the form for use in your AJAX call, then you need to do as @Sippy suggests and retrieve it via JavaScript:

它返回 null 因为它null。用户最终将输入到表单中的数据在页面呈现时(以及您对Json.Encode(Model)运行的调用)不可用。JavaScript 之类的东西在客户端运行,而所有 Razor 东西在发送到客户之前都在服务器端运行。如果您想从表单中获取用户输入的数据以在 AJAX 调用中使用,那么您需要按照@Sippy 的建议进行操作并通过 JavaScript 检索它:

$('form').serializeObject();

Also, in case you do need to actually encode the model when rendering (for maybe use with something like Knockout), you don't need to set it as a string and then parse the string. Just set it as a regular JavaScript object. That's all JSON is anyways:

此外,如果您确实需要在渲染时对模型进行实际编码(可能与 Knockout 之类的东西一起使用),则无需将其设置为字符串然后解析该字符串。只需将其设置为常规 JavaScript 对象即可。无论如何,这就是所有 JSON:

var model = @Html.Raw(Json.Encode(Model));

回答by Luca

This sample, encode a model (that is a List<My>) and POST it to an action as a Json object named model.

此示例对模型(即 a List<My>)进行编码,并将其作为名为 model 的 Json 对象发布到操作中。

var jsonModel = '@Html.Raw(Json.Encode(Model))';
    var id = rowid;
    $.ajax({
        url: 'DeleteRows',
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        dataType: 'html',
        data: '{ "model": { "rows":' + jsonModel + '}}'
    })
    .success(function (result) { $("#grdRows").empty(); $("#grdRows").html(result); })
    .error(function (xhr, ajaxOptions, thrownError) { alert(xhr.status + ' - ' + ajaxOptions + ' - ' + thrownError); alert(xhr.responseText); });