I've got an array of strings in JS. All the members are actually numbers.
My controller has an int[] parameter.
I send it from jquery:
$.ajax({url: someUrl, data: {ids : JSON.stringify(id_array) }, ...)
and I receive it using
public ActionResult MyAction(int[] ids) { ...
The parameter doesn't get filled, I've checked, the Request.Form["ids"]
contains "[\"25\",\"26\"]"
, the string represention of the JSON array.
Is there any way to do this automatically without a lot of int parsing?
Have you tried not stringifying the array and letting mvc's default model binding do the magic
$.ajax({url: someUrl, data: {ids : id_array }, ...)
I'm pretty sure .net MVC will see the array and see it is an array of ints and map it to your array of ints correctly
For MVC3 you need to configure jQuery to use traditional, "shallow" serialisation.. See here.
Client-side AJAX request:
jQuery.ajaxSettings.traditional = true; //enable "shallow" serialisation globally
$.get("someUrl", {ids : id_array });
Action Method:
public ActionResult MyAction(string[] ids) { ... }
You can do this in two different ways
1. Use $.ajax to post data to your action
$.ajax({ url: '/myController/myAction', dataType: 'json', type: 'POST', contentType: 'application/json; charset=utf-8', traditional: true, data: $.toJSON(json), success: function (data, textStatus, jqXHR) { ... } });
Your action should look like this one
public class myController
{
[HttpPost]
public ActionResult myAction(List<int> json)
{
....
}
}
2. Use $.post to post your data
$.post( '/myController/myAction', { json: $.toJSON(products) }, function (data) { ... });
In your action you should deserialize JSON string
public class myController
{
public ActionResult myAction(string json)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<int> list = serializer.Deserialize<List<int>>(json);
}
}
You need to download and include jquery.json-2.2.min.js to your code.
http://code.google.com/p/jquery-json/downloads/detail?name=jquery.json-2.2.min.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With