DeAn DeAn - 1 month ago 9
Javascript Question

How to pass string array to controller using ajax?

// something defined deleteArr and pass values to it
var postData = { deleteArr: deleteArr };
if(deleteArr.length > 0)
{
$.ajax({
url: "@Url.Action("Delete", "ASZ01")",
type: "POST",
data: postData,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}


The above code is javascript.
Until $.ajax begin I can confirm that values in array is correct in immediate window,but when it comes to error: I got "undefined".
And the following is my function in controller

public void Delete(List<string> deleteArr)
{
service.Delete(deleteArr);
}


The second question is that I set breakpoint on that function but it can't stop.
I think maybe my ajax form is wrong?

Answer

Small change to your postData

var postData = { deleteArr: JSON.stringify(deleteArr) };

Idea is to convert your array data into string format ie:JSON and posting to the server, The default Model binder of MVC framework will handle the part to convert them into List<string> for you