I hava a javascript array in my Razor view, and I am calling an GET action of controller from my MVC view using $.ajax. What should be the parameter type of the Controller action that will accept the Javascript array passed from view. I tried to keep it as "object", but it is showing it as "[object]" only and showing no properties at all. Any idea of how to achieve this?
2 Answers
It completely depends upon the type of the values in your array.
Say, if you have an array of integers, like this:
var intArray = [1,2,3,4]
Then, in your controller, you'd have a List<int>
as your parameter type, the Controller is clever enough to figure out the conversion for you.
However, if you're wanting something more advanced, which I'm guessing you are, such as:
var customArray = [{hello: "world", foo: "bar"}]
Then it's best to create a custom object in .NET, with hello
and foo
as properties, such as:
public CustomObject {
public string hello { get; set; }
public string foo { get; set; }
}
Then you can use CustomObject
, or List<CustomObject>
as your parameter type and the Controller will map the properties for you... like magic.
Just pass it in ajax and add traditional: true,
var ids = [0,1,2,3];
$.ajax({
url: '@Url.Action("SomeAction", "Home")',
type: 'POST',
traditional: true,
data: { array: ids },
...
Controller
public ActionResult SomeAction(int[] array){}
For object array
var objs = JSON.stringify(your_objects);
$.ajax({
url: '@Url.Action("SomeAction", "Home")',
type: 'POST',
data: { array: objs },
...
controller
public ActionResult SomeAction(List<YourObjectType> array){}
Check HERE
-
thanks, this just worked out for me, however, I have a similar thing but here now my Javascript array is actually a key-value pair..– NirmanCommented May 7, 2013 at 9:31
{object}
to an[array]
before passing it.