I'm trying to send the selected values of a chosen multi select list to an Action in my Controller. I've verified val() does show me an array of selected values like ["33","175"] when I print out to the console but the Action's argument is always null. I tried changing the argument type to object and verified it's not null but I can't parse the values. Any suggestions? Please and thanks!
Ajax call:
$(".chosen-select").on("change", function (event, params) {
console.log($(".chosen-select").val());
$.ajax({
url: '@Url.Action("BDOReferralSourcesTableHTML","ReferralNetwork")',
type: 'GET',
dataType: 'json',
cache: false,
data: { bdoIds: $(".chosen-select").val() },
success: function (response) {
if (response.length > 0) {
alert(response);
}
else {
alert("response length zero");
}
}
});
});
Controller Action:
public ActionResult BDOReferralSourcesTableHTML(string[] bdoIds)
{
return Content("<b>test</b>", "text/html");
}
you have to set traditional
property of ajax to true
:
$.ajax({
url: '@Url.Action("BDOReferralSourcesTableHTML","ReferralNetwork")',
type: 'GET',
dataType: 'json',
cache: false,
traditional:true,
data: { bdoIds: $(".chosen-select").val() },
success: function (response) {
if (response.length > 0) {
alert(response);
}
else {
alert("response length zero");
}
}
});
you can also set it globally so there is no need to specify it in every ajax call:
$.ajaxSetup({
traditional:true
});
UPDATE:
Following is the reason why you need to set traditional:true
:
jQuery 1.4 adds support for nested param serialization in
jQuery.param
, using the approach popularized by PHP, and supported by Ruby on Rails. For instance,{foo: ["bar", "baz"]}
will be serialized as “foo[]=bar&foo[]=baz”.In jQuery 1.3,
{foo: ["bar", "baz"]}
was serialized as “foo=bar&foo=baz”. However, there was no way to encode a single-element Array using this approach. If you need the old behavior, you can turn it back on by setting the traditional Ajax setting (globally viajQuery.ajaxSettings.traditional
or on a case-by-case basis via the traditional flag).
Details can be seen jQuery 1.4 Released – Full Release Notes in Ajax section.
You can also see the explanation here. jQuery 1.4 breaks ASP.Net MVC actions with array parameters
来源:https://stackoverflow.com/questions/25086481/passing-chosen-multi-select-values-to-controller-action