How to send a list of int with jQuery to ASP.net MVC Default Model Binder

耗尽温柔 提交于 2020-01-09 19:22:10

问题


When I send a list of int's with jQuery like this:

$.ajax('@Url.Action("Execute")', {
    type: 'POST',
    data: {
        pkList: [1,2,3]
    }
});

Then jQuery will transform the pkList object and send it by post like this:

pkList[]:1
pkList[]:2
pkList[]:3

Which would be fine if the server is PHP but I use Asp.NET MVC3 and try to get these values with the default model binder:

public ActionResult Execute(ICollection<int> pkList)

But pkList is always null, it seems that the default model binder cannot bind it.

How do I solve this correctly?


ADDED SOLUTION

I used the solution from Darin Dimitrov with setting the traditional option in jQuery:

$.ajax('@Url.Action("Execute")', {
    type: 'POST',
    traditional: true,
    data: {
        pkList: [1,2,3]
    }
});

Now jQuery doesn't add the [] to the parameters anymore and they are sent like this:

pkList:1
pkList:2
pkList:3

And the MVC default model binder gets the values correctly.

Hope this helps someone.


回答1:


You could use a JSON request as it will allow you to send any complex objects you wish:

$.ajax({
    url: '@Url.Action("Execute")',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({ pkList: [1, 2, 3] }), // you could throw any javascript object you like here
    success: function(result) {
        // process the results
    }
});

The JSON.stringify method is built in modern browsers and if you want to support legacy browsers you could include the json2.js script to your site.

And to answer your question you could use set the traditional: true option to indicate to jQuery to fallback to traditional serialization of parameters since this has changed in jQuery 1.4 and if you are using a later version you have the possibility to switch back to the way parameters are serialized:

$.ajax({ 
    url: '@Url.Action("Execute")',
    type: 'POST',
    data: {
        pkList: [1, 2, 3]
    },
    traditional: true
});



回答2:


Adding this because @Darin miss the controller action.

Java script code:

function sendArray() {
    var list = ["a", "b"];

    $.ajax({
        url: '@Url.Action("ActionName")',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ list }),
        dataType: "json",
        success: function (response) {},
        error: function (response) {}
    });
}

C# code

[HttpPost]
public ActionResult ActionName(List<string> list)
{
    return View();
}



回答3:


Phil Haack has a great article on his blog that should point you in the right direct.

Model Binding To A List



来源:https://stackoverflow.com/questions/7931832/how-to-send-a-list-of-int-with-jquery-to-asp-net-mvc-default-model-binder

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