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

6 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
  4. Hi, how I could pass List to Action, the List is nested in a Model: @Model.MyObjectList, I tried this:

    var value = "some text";
    var params = {
    myObjectList: JSON.stringify('@Model.MyObjectList'),
    textFilter: value
    };
    $.ajax({
    url: '@Url.Action("MyAction", "MyController")',
    type: "GET",
    traditional: true,
    data: params,
    datatype: "json",
    ContentType: "application/json;utf-8",
    success: function (result) {
    // add result (List) to WebGrid
    },
    failure: function (response) {
    alert(response.responseText);
    },
    error: function (response) {
    alert(response.responseText);
    }
    });
    }

    MyController code:


    public JsonResult MyAction(List myObjectList, string textFilter)
    {
    List myObjectFiltered= new List();
    if (myObjectList != null && myObjectList.Count > 0)
    {
    myObjectFiltered = myObjectList.Where(p => p.Id.ToString().Contains(textFilter)).ToList();
    }
    return Json(myObjectFiltered);
    }
    I tried with type: "POST" and only string array but exist an error, with type: "GET" and only string array working.
    Thanks

    ReplyDelete