Afs*_*neh 5 javascript arrays ajax asp.net-mvc jquery
我想使用ajax将具有其他形式数据的对象数组发送到MVC动作。
var arr = [
{ Name: "a", IsActive: "true" },
{ Name: "b", IsActive: "false" },
{ Name: "c", IsActive: "true" },
{ Name: "d", IsActive: "false" },
{ Name: "e", IsActive: "true" }
];
Run Code Online (Sandbox Code Playgroud)
和其他一些表单字段数据。我尝试获取和附加这样的表单数据:
$(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;
});
Run Code Online (Sandbox Code Playgroud)
但是在服务器端,我在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; }
}
Run Code Online (Sandbox Code Playgroud)
和我的行动:
[HttpPost]
public JsonResult CreateType(ProductTypeCreateModel productType)
{
...
}
Run Code Online (Sandbox Code Playgroud)
谢谢。
小智 1
为了DefaultModelBinder绑定数组中的数据,您需要按以下格式附加名称和值
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
Run Code Online (Sandbox Code Playgroud)
以与访问服务器端代码中的值完全相同的方式(即,要获取集合中Name第二个的值,您可以使用Feature
string name = productType.Features[1].Name; // returns "b"
Run Code Online (Sandbox Code Playgroud)
参数的名称是productType,所以只需去掉它,剩下的就是需要如何传入名称FormData。
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |