Monday, May 20, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  20] [ 4]  / answers: 1 / hits: 53207  / 11 Years ago, wed, january 22, 2014, 12:00:00

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(
{
type: POST,
url: ../Home/SaveTable,
data: { function_param: countryArray }
});


Problem is, countryArray is a global array in the JavaScript View and I've check that it has elements in it before being passed. However, when the saveTable function receives the array, the function says it received a null string[] array.



I only know that passing arrays from the Controller to the View, you serialize complex data types with return Json(data, JsonRequestBehavior.AllowGet); and then de-serialize it by setting it to a var variable.



So I probably have to do it for this as well, but how to?



Edit 1:



Here is the shortened version of the SaveTable function:



public string SaveTable(string[] function_param)
{
if (function_param != null && function_param > 0)
{
//some code
return Success;
}

//The following code will run if it's not successful.
return There must be at least one country in the Region.;
//Yeah it's always returning this b/c function_param is null;
}

More From » c#

 Answers
8

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}),
});

[#73012] Tuesday, January 21, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mitchellg

Total Points: 235
Total Questions: 117
Total Answers: 106

Location: Fiji
Member since Wed, Jul 14, 2021
3 Years ago
;