[MVC3]Can't bind JSON array

2019-09-06 14:23发布

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 ??

4条回答
Anthone
2楼-- · 2019-09-06 14:48

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() {
       // ...
    }
});
查看更多
Emotional °昔
3楼-- · 2019-09-06 14:56

You have to apply JSON.stringify

$.post('@Url.Action("Save", "Users")', JSON.stringify({'IDs' : [1, 2, 3]}), function() {}); 
查看更多
何必那么认真
4楼-- · 2019-09-06 14:57

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() {
        // ...
    }
})
查看更多
We Are One
5楼-- · 2019-09-06 14:58

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

查看更多
登录 后发表回答