[MVC3]Can't bind JSON array

☆樱花仙子☆ 提交于 2020-01-07 08:32:35

问题


I thought MVC3 can bind JSON data to model by default.

but this code

server:

[HttpPost]
public ActionResult Save(IList<int> IDs)
{
    return null;
}

client:

$.post('@Url.Action("Save", "Users")', {'IDs' : [1, 2, 3]}, function() {});

don't work. Why ??


回答1:


Your code sends IDs[]=1&IDs[]=2&IDs[]=3.

You need send IDs=1&IDs=2&IDs=3.

Set traditional:true parameter to use the traditional style of param serialization.

$.ajax({
    url: '@Url.Action("Save", "Users")',
    type: 'post',
    data: {'IDs' : [1, 2, 3]},
    traditional:true,
    success: function() {
        // ...
    }
})



回答2:


You need to send your data as application/json:

$.ajax({
    type: 'post',
    url: '/Users/Save'
    data: JSON.stringify({'IDs' : [1, 2, 3]}),
    contentType: 'application/json; charset=utf-8',
    success: function() {
       // ...
    }
});



回答3:


This might be the same as the problem I ran into a while ago. Check out this SO question Post Array as JSON to MVC Controller




回答4:


You have to apply JSON.stringify

$.post('@Url.Action("Save", "Users")', JSON.stringify({'IDs' : [1, 2, 3]}), function() {}); 


来源:https://stackoverflow.com/questions/12263554/mvc3cant-bind-json-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!