How can I send int array from ajax to c# mvc?

谁说胖子不能爱 提交于 2019-12-04 23:52:44
Daniel
$.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.

VMAtm

Try solution from this question:

Set the traditional property to true before making the get call. i.e.:

jQuery.ajaxSettings.traditional = true

$.get('/controller/MyAction', 
    { vals: arrayOfValues }, 
    function (data) {
      ...
    }

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>(',');
    ...
}
Ben Parsons

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.

jQuery GET Syntax
JS Array toString() syntax

Try this solution :

var Array = [10, 20, 30];

$.ajax({
    type: "Post",
    datatype: "Json",
    url: <Url of the action>,
    data: JSON.stringify(Array),
    contentType: 'application/json; charset=utf-8',

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!