Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
You should include some code. – MDeSchaepmeester May 7 at 8:52
yes, agreed.. but its difficult to separate out only the code of interest. if anyone having instant idea.. – Nirman May 7 at 8:54
convert that {object} to an [array] before passing it. – Omar May 7 at 8:58

2 Answers

up vote 2 down vote accepted

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.

share|improve this answer

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

share|improve this answer
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.. – Nirman May 7 at 9:31
1  
You want to pass object array, right? – AliRıza Adıyahşi May 7 at 9:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.