我想使用 ajax 将包含其他形式数据的对象数组发送到 MVC 操作。
var arr = [
{ Name: "a", IsActive: "true" },
{ Name: "b", IsActive: "false" },
{ Name: "c", IsActive: "true" },
{ Name: "d", IsActive: "false" },
{ Name: "e", IsActive: "true" }
];
和一些其他表单字段数据。 我试过像这样获取和附加表单数据:
$(document.body).delegate("form#mainFormCreate", "submit", function () {
var formData = new FormData($("form#mainFormCreate")[0]);
var arr = [
{ Name: "a", IsActive: "true" },
{ Name: "b", IsActive: "false" },
{ Name: "c", IsActive: "true" },
{ Name: "d", IsActive: "false" },
{ Name: "e", IsActive: "true" }
];
jQuery.each(arr, function (key, value) {
formData.append('Features[' + key + ']', value);
});
$.ajax({
url: '@Url.Action("CreateType", "Admin")',
type: 'POST',
data:formData,
success: function (result) {
....
},
error: function (x, t, e) {
....
},
cache: false,
contentType: false,
processData: false
});
return false;
});
但在服务器端,我得到一个包含 5 个元素的数组,其 Features 属性中的值为空。 这是我的服务器端代码。我的对象:
public class ProductTypeCreateModel
{
public string ProductTypeName { get; set; }
public List<Feature> Features { get; set; }
}
public class Feature
{
public string Name { get; set; }
public bool IsActive { get; set; }
}
和我的行动:
[HttpPost]
public JsonResult CreateType(ProductTypeCreateModel productType)
{
...
}
谢谢。
最佳答案
为了让 DefaultModelBinder
绑定(bind)数组中的数据,您需要按照以下格式附加名称和值
formData.append('Features[0].Name', 'a');
formData.append('Features[0].IsActive', true);
formData.append('Features[1].Name', 'b');
formData.append('Features[1].IsActive', false);
... // etc
以与访问服务器端代码中的值完全相同的方式(即获取集合中第二个Feature
的Name
,您将使用
string name = productType.Features[1].Name; // returns "b"
参数的名称是productType
,所以只需去掉它,剩下的就是如何在FormData
中传递名称。
关于javascript - 如何使用 ajax 发送对象数组和其他表单数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38495416/