Reputation: 13855
I am trying to recieve the selected values of my multi-select box. Through Ajax call.
Below is my test action
public ActionResult MultiSelect(String[] test)
{
String[] arrayornot = test; //null being recieved. or the string if hardcoded
}
the Jquery
alert($('#county').val()); // London, Brim
$.ajax({
url: '@Url.Action("MultiSelect", "APITest")',
type: 'GET',
cache: false,
data: { test: $('#county').val()},
success: function (result) {
$('#myDiv').html(result);
}
});
if I hardcode it to a string, it works fine. with String[]
or String
endpoint. If it passes in a comma seperated string, i can sort it on server side. or a string array is better.
Upvotes: 0
Views: 1279
Reputation: 21
The error is the $Ajax configuration set the method traditional: true then your problem is solved.
var selectedItems=$('#county').val();
$.ajax({
url: '@Url.Action("MultiSelect", "APITest")',
type: 'POST',
cache: false,
traditional: true,
data: { test: JSON.stringify(selectedItems)},
success: function (result) {
$('#myDiv').html(result);
}
});
Upvotes: 2
Reputation: 66
I had the same issue you were having. I found the answer in the following link.
Basically what you need to do is to add the following line and the values will pass as an array.
jQuery.ajaxSettings.traditional = true;
Upvotes: 1
Reputation: 1935
Instead of using string[]
(string array) in method parameter. use string
parameter. and convert this comma separated string in to an array on server side.
use following code,
Server side,
public ActionResult MultiSelect(string test)
{
return View();
}
JQuery Code,
$.ajax({
url: '@Url.Action("MultiSelect", "OrderCreation")',
type: 'GET',
cache: false,
data: { test: $('#county').val().toString() },
success: function (result) {
$('#myDiv').html(result);
}
});
Upvotes: 1
Reputation: 22619
I would use javascript array and convert into JSON string
var selectedItems=$('#county').val(); // returns the array of selected items
Then use JSON.stringify method
$.ajax({
url: '@Url.Action("MultiSelect", "APITest")',
type: 'GET',
cache: false,
data: { test: JSON.stringify(selectedItems)},
success: function (result) {
$('#myDiv').html(result);
}
});
JSON.Stringify is not available in IE 7. Please use JSON2.js
Hope this will help you!
Upvotes: 1