I have the following controller that I am posting to in a form via AJAX:
[HttpPost]
public ActionResult Create(List<int> listOfSTuff)
{
try
{
service.Create(listOfSTuff);
}
catch
{
return null;
}
return Json(new { gid = 7 }); // hardcoded for simplicity
}
I am having a hard time with my jQuery AJAX post making the List
data type compatible with the post data. Here is my jQuery/JavaScript code:
var listOfStuff = [1, 2, 3];
$.ajax({
type: 'POST',
url: '/MyController/Create',
data: listOfStuff,
success: function(data) {
alert(data.gid);
},
error: alert(':('),
dataType: 'json'
});
I know that the AJAX post to the controller is working because I get a gid
but I do no开发者_开发知识库t see the array elements 1
or 2
or 3
saved in the database. It does not appear that the controller likes my JavaScript array that is being passed over. Can anyone suggest how the data structure should look like from the frontend to make it compatible with the List
that the controller action is expecting?
Make your listOfStuff declared as such:
var listOfStuff = {postedValues: [1, 2, 3]};
It works better to format your posted data as a proper JSON object before posting it to the controller. so now:
data: listOfStuff
, will post a proper JSON string
and change the parameter name in your Controller to be:
[HttpPost]
public ActionResult Create(List<int> postedValues)
{
}
Hope it works for you.
It turns out that I was missing a critical parameter in the jQuery AJAX call that makes this work:
There is a traditional
attribute that is false
by default but it has to be set to true
which uses the traditional style of param serialization.
精彩评论