How can I send int array from $.ajax to c# mvc?
-
I tried 3-4 examples I can't run it. What can be a reason?Anton Lyhin– Anton Lyhin2012-02-02 09:28:01 +00:00Commented Feb 2, 2012 at 9:28
-
[Ajax] public bool example(int[] ints)Anton Lyhin– Anton Lyhin2012-02-02 09:28:19 +00:00Commented Feb 2, 2012 at 9:28
-
1please give more detail of what you have tried and what result you are seeing, including code.Ben Parsons– Ben Parsons2012-02-02 09:47:46 +00:00Commented Feb 2, 2012 at 9:47
-
I want to check all examples, but most of them send null to c# method.Anton Lyhin– Anton Lyhin2012-02-02 10:01:06 +00:00Commented Feb 2, 2012 at 10:01
-
I think @Darin Dimitrov has given the appropriate answer here for thisMuhammad Ashikuzzaman– Muhammad Ashikuzzaman2016-05-26 10:25:18 +00:00Commented May 26, 2016 at 10:25
5 Answers
$.ajax({
url: <Url of the action>,
type: "POST",
data: JSON.stringify([1,2,3]),
dataType: "json",
contentType: 'application/json; charset=utf-8'
});
and in the action.
public ActionResult ReceiveIntArray(int[] ints)
{
...
}
mvc should parse the json automatically.
check out this question.
4 Comments
Try solution from this question:
Set the
traditionalproperty to true before making the get call. i.e.:jQuery.ajaxSettings.traditional = true $.get('/controller/MyAction', { vals: arrayOfValues }, function (data) { ... }
1 Comment
The way I'm doing it is with a simple input:hidden element
<input type="hidden" name="elements" value='@String.Join(",", ViewBag.MyArray)' />
And in the JavaScript code I'm passing it as a string:
$.ajax({
type: "POST",
url: '/Controller/Method',
data:
{
recipients: $("input[name=elements]").val()
},
traditional: true,
success: updateSelected
});
And finally I just Split the elements like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Method(string elements)
{
IList<long> selected = elements.Split<long>(',');
...
}
Comments
The simplest way would be to send a delimited (commas, possibly) string list of the ints as an argument on a GET request, then use Sting.Split() to parse them on your C# MVC receiver.
So, for example
$.get("/path-to/receiver/", { myArray: myArray.toString() } );
Then, on the server, use
string[] stringArray = Request.QueryString["myArray"].ToString().Split(',')
to extract the values to a string array, then Int32.TryParse to finally get an array of ints.