![](/img/trans.png)
[英]How can I send a javascript array to a PHP script using Ajax along with other non-array data?
[英]How to send an array of objects along with other formdatas using ajax?
我想使用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)
{
...
}
谢谢。
首先序列化您的数据,尝试JSON.stringify(formData)
您可以序列化数据,也可以将其包装在一个对象中并发送
var arr = [
{ Name: "a", IsActive: "true" },
{ Name: "b", IsActive: "false" },
{ Name: "c", IsActive: "true" },
{ Name: "d", IsActive: "false" },
{ Name: "e", IsActive: "true" }
];
$.ajax({
url: '@Url.Action("CreateType", "Admin")',
type: 'POST',
data:{data: arr},
success: function (result) {
....
},
error: function (x, t, e) {
....
},
cache: false,
contentType: false,
processData: false
});
为了使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
与访问服务器端代码中的值的方式完全相同(即,要获取集合中第二个Feature
的Name
,您可以使用
string name = productType.Features[1].Name; // returns "b"
参数的名称为productType
,因此将其删除,剩下的就是如何在FormData
传递名称。
使用以下代码:
$('form').serializeArray()` or `$('form').serialize()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.