【发布时间】:2016-11-24 12:37:09
【问题描述】:
我想使用 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;
});
但在服务器端,我在 Features 属性中获得了一个包含 5 个元素的数组,这些元素具有空值。 这是我的服务器端代码。我的对象:
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)
{
...
}
谢谢。
【问题讨论】:
-
你能把你在Controller中的post方法发给我们吗,同时你忽略了modelBinder的规则。
-
它需要采用
formData.append( 'Features[0].Name', 'a'); formData.append( 'Features[0].IsActive', true);等格式(假设Features是一个包含string Name和bool IsActive的复杂对象 -
感谢斯蒂芬,它成功了。
标签: javascript jquery arrays ajax asp.net-mvc