$('#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);
}
thanks very helpfull article
ReplyDeleteHI 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.
ReplyDeletecheck the updated post regarding multi-dimensional array
DeleteThis really really helped me out thankyou very much
ReplyDeleteReally nice article, can you please guide how to get an array of arrays in controller action? like:
ReplyDeletedata: { Title: 'Greatest', Categories: [cat1:['show', 'on', 'earth'], cat2:['show1', 'on1', 'earth1']] }
Thank you,
Dinesh Sharma
Hi, how I could pass List to Action, the List is nested in a Model: @Model.MyObjectList, I tried this:
ReplyDeletevar 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