0

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?

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

2 Answers 2

3

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.

3

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

1
  • 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
    Commented May 7, 2013 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.