简体   繁体   English

Model 绑定无法绑定字符串数组,当发布为 JSON object

[英]Model binding is not able to bind string array when post as JSON object

I have the following jQuery extension to serialize form as Json object我有以下 jQuery 扩展序列化形式为 Json object

(function () {
    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if ((typeof (this.value) === "boolean") ||
                    (typeof (this.value) === "string" && this.value != undefined && (this.value.toLowerCase() === "true" || this.value.toLowerCase() === "false"))) {
                    o[this.name] = ((o[this.name] == "true") | (this.value == "true")) ? true : false; //Sets value to true if one of two bits is true
                }
                else {
                    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;
    };
})(jQuery)

Then i have Html form然后我有 Html 表格

<form id="myform">
    <input name"AccountNumbers[0]" value="1111" />
    <input name"AccountNumbers[1]" value="2222" />
    // some other properties
</form>

Then using Ajax i am posting the form to server然后使用 Ajax 我将表单发布到服务器

var obj = $("#myform").serializeObject();
   $.ajax({
            type: "POST",
            data: JSON.stringify(obj),
            url: "/save",
            contentType: "application/json; charset=utf-8",
            processData: true,
            cache: false
        })

The serializeObject method create json object as serializeObject方法创建 json object 作为

{
   "AccountNumbers[0]: "1111",
   "AccountNumbers[1]: "2222"
  ....
  ....      
}

I am using ASP.NET Core.我正在使用 ASP.NET 核心。 So on server i have Controller action method所以在服务器上我有 Controller 操作方法

    public class MyModel
    {
        public string[] AccountNumbers {get;set;}

        // some other properties
    }

    [HttpPost]
    public async Task<IActionResult> Save([FromBody]MyModel model)
    {
        // do something
    }

ISSUE: On server, model's all the properties are populated except AccountNumbers .问题:在服务器上,模型的所有属性都被填充,除了AccountNumbers Somehow the model binding is not able to bind the string array. model 绑定无法绑定字符串数组。

UPDATE 1更新 1
as pointed out in the comments below issue was the array structure.正如下面评论中指出的那样,问题是数组结构。 I have changed my jQuery extension however it works for one level.我已经更改了我的 jQuery 扩展名,但它适用于一个级别。 But if i have hierarchy then it will not work但是如果我有层次结构那么它就不起作用

(function () {
    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            var name = this.name;
            var val = this.value;
            if (name && name.indexOf("[") > -1) {
                name = name.substr(0, name.lastIndexOf("["));
            }

            if (o[name]) {
                if ((typeof (val) === "boolean") ||
                    (typeof (val) === "string" && val != undefined && (val.toLowerCase() === "true" || val.toLowerCase() === "false"))) {
                    o[name] = ((o[name] == "true") | (val == "true")) ? true : false; //Sets value to true if one of two bits is true
                }
                else {
                    if (!o[name].push) {
                        o[name] = [o[name]];
                    }
                    o[name].push(val || '');
                }
            } else {
                o[name] = val || '';
            }
        });
        return o;
    };
})(jQuery)

The extension will not work for该扩展程序不适用于

<input name="Person[0].AccountNumber[0]" value="1111" />
<input name="Person[0].AccountNumber[1]" value="2222" />
<input name="Person[1].AccountNumber[0]" value="3333" />
<input name="Person[1].AccountNumber[1]" value="4444" />

You will need to update your AccountNumbers property on your JSON body to be an array type.您需要将 JSON 主体上的AccountNumbers属性更新为数组类型。 ASP.NET Core is seeing each of the indexed AccountNumbers properties as different properties and not part of a collection. ASP.NET Core 将每个索引的AccountNumbers属性视为不同的属性,而不是集合的一部分。

Something like this should work:这样的事情应该有效:

{
  AccountNumbers: ["1111", "2222"]
}

If this were a GET request, you could pass each item of the array as query string parameters with the same name.如果这是一个 GET 请求,您可以将数组的每一项作为具有相同名称的查询字符串参数传递。 For example:例如:

/save?AccountNumbers=1111&AccountNumbers=2222

Note: This approach will not work with JSON POST bodies as duplicate keys aren't allowed in valid JSON.注意:此方法不适用于 JSON POST 主体,因为在有效的 JSON 中不允许重复键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM