user2910983 user2910983 - 4 months ago 11
jQuery Question

How to send an array of objects along with other formdatas using ajax?

I want to send an array of objects with other form data to MVC action using ajax.

var arr = [
{ Name: "a", IsActive: "true" },
{ Name: "b", IsActive: "false" },
{ Name: "c", IsActive: "true" },
{ Name: "d", IsActive: "false" },
{ Name: "e", IsActive: "true" }
];


and some other form fields data.
I tried getting and attaching form data like this:

$(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;
});


But in server side, I get an array of 5 element's with null values in Features property.
here is my server side code.my object:

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; }
}


and my action:

[HttpPost]
public JsonResult CreateType(ProductTypeCreateModel productType)
{
...
}


Thank.

Answer

In order for the DefaultModelBinder to bind the data in the array, you need to append the name and values in the following format

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

in exactly the same way that you would access the values in server side code (i.e. to get the Name of the second Feature in the collection, you would use

string name = productType.Features[1].Name; // returns "b"

The name of the parameter is productType, so just strip that, and whats left is how the name needs to be passed in FormData.