Tuesday, May 17, 2011

Pass array from jQuery to ASP.NET MVC controller

The View ( must pass traditional(set to true) property to ajax parameter ):

$('#Simple').click(function () {

    $.ajax({
        url: '/Home/Simple/',
        type: 'POST',
        traditional: true,
        data: { Title: 'Greatest', Categories: ['show', 'on', 'earth'] },
        dataType: 'json',
        success: function (data) {
            alert(data.Title);
            for (i = 0; i < data.Categories.length; ++i)
                alert(data.Categories[i]);
        }
    });

});


The Controller:
[HttpPost]
public JsonResult Simple(Article a)
{
    return Json(a);
}

The Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace JquerySendBatch.Models
{
    public class Article
    {
        public string Title { get; set; }
        public string[] Categories { get; set; }
    }
}


If need to return multi-dimensional array, pass it as JSON object:


<input type='button' id='Simple' value='hello'/>


<script>
    $('#Simple').click(function () {

        var theData = [['a', 'b', 'c', 'z'], ['d', 'e', 'f', 'y']];
        var json = JSON.stringify(theData);

        $.ajax({
            url: '/Home/Test',
            type: 'POST',

            contentType: 'application/json; charset=utf-8',
            data: json,

            dataType: 'json',
            success: function (data) {
                for (i = 0; i < data.length; ++i) {
                    alert('wow');
                    for (j = 0; j < data[i].length; ++j)
                        alert(data[i][j]);
                }


            },
            error: function (a, b, c) {
                alert(a + ' ' + b + ' ' + c);
            }

        });

    });

</script>



Then on your controller:

[HttpPost]
public JsonResult Test(string[][] Categories)
{
    return Json(Categories);
}

5 comments:

  1. HI thank u so much but i having a issue is passing a array of array like [['a','b','c'],['d','e','f']] can u please help on this. ?? thank you so much for you note.

    ReplyDelete
    Replies
    1. check the updated post regarding multi-dimensional array

      Delete
  2. This really really helped me out thankyou very much

    ReplyDelete
  3. Really nice article, can you please guide how to get an array of arrays in controller action? like:
    data: { Title: 'Greatest', Categories: [cat1:['show', 'on', 'earth'], cat2:['show1', 'on1', 'earth1']] }

    Thank you,
    Dinesh Sharma

    ReplyDelete