我有以下jQuery扩展来将表单序列化为Json对象
(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)
然后我有HTML格式
<form id="myform">
<input name"AccountNumbers[0]" value="1111" />
<input name"AccountNumbers[1]" value="2222" />
// some other properties
</form>
然后使用Ajax将表单发布到服务器
var obj = $("#myform").serializeObject();
$.ajax({
type: "POST",
data: JSON.stringify(obj),
url: "/save",
contentType: "application/json; charset=utf-8",
processData: true,
cache: false
})
[serializeObject
方法创建json对象为
{
"AccountNumbers[0]: "1111",
"AccountNumbers[1]: "2222"
....
....
}
我正在使用ASP.NET Core。所以在服务器上,我有控制器操作方法
public class MyModel
{
public string[] AccountNumbers {get;set;}
// some other properties
}
[HttpPost]
public async Task<IActionResult> Save([FromBody]MyModel model)
{
// do something
}
问题:在服务器上,除AccountNumbers
外,模型的所有属性均已填充。模型绑定无法以某种方式绑定字符串数组。
UPDATE 1正如下面的评论所指出的那样,问题是数组结构。我已经更改了jQuery扩展名,但是它只适用于一个级别。但是,如果我有层次结构,那么它将不起作用
(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)
该扩展名不适用于
<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" />
您需要将JSON主体上的AccountNumbers
属性更新为数组类型。 ASP.NET Core将每个索引的AccountNumbers
属性视为不同的属性,而不是集合的一部分。