In MVC 4, how do you pass a JavaScript array in the View to a function in the Controller with AJAX?
This doesn\'t seem the work:
$.ajax(
{
You should use on your controller:
public string SaveTable(object[] function_param)
{
//some code
}
Should do the work, it's for future users.
You need to set traditional: true
when serializing arrays.
$.ajax({
type: "POST",
traditional: true,
url: "../Home/SaveTable",
data: { function_param: countryArray }
});
Found this good explanation on what traditional: true
does: https://stackoverflow.com/a/5497151/2419531
EDIT:
If you don't want to use traditional: true
, you can pass the data as string using JSON.stringify
and specifying the contentType
:
$.ajax({
type: "POST",
url: "../Home/SaveTable",
contentType: 'application/json',
data: JSON.stringify({function_param: countryArray}),
});
your Ajax :
$.ajax({
type: "POST",
url: "../Home/SaveTable",
contentType: 'application/json',
data: {function_param: JSON.stringify(countryArray)},
});
in your controller:
using Newtonsoft.Json;
public string SaveTable(string function_param)
{
dynamic func_param = JsonConvert.DeserializeObject(function_param)
}
then you will be able to do a foreach in your controller.