jQuery 如何将 int 数组从 ajax 发送到 c# mvc?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9109544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I send int array from ajax to c# mvc?
提问by Anton Lyhin
How can I send int array from $.ajax to c# mvc?
如何将 int 数组从 $.ajax 发送到 c# mvc?
回答by 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.
mvc 应该自动解析 json。
check out this question.
看看这个问题。
回答by 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) { ... }
traditional
在进行 get 调用之前将该属性设置为 true。IE:jQuery.ajaxSettings.traditional = true $.get('/controller/MyAction', { vals: arrayOfValues }, function (data) { ... }
回答by 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.
最简单的方法是将整数的分隔(可能是逗号)字符串列表作为 GET 请求的参数发送,然后用于Sting.Split()
在 C# MVC 接收器上解析它们。
So, for example
$.get("/path-to/receiver/", { myArray: myArray.toString() } );
所以,例如
$.get("/path-to/receiver/", { myArray: myArray.toString() } );
Then, on the server, use
然后,在服务器上,使用
string[] stringArray = Request.QueryString["myArray"].ToString().Split(',')
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.
将值提取到一个字符串数组,然后Int32.TryParse
最终得到一个整数数组。
回答by MonkeyCoder
The way I'm doing it is with a simple input:hidden
element
我这样做的方式是使用一个简单的input:hidden
元素
<input type="hidden" name="elements" value='@String.Join(",", ViewBag.MyArray)' />
And in the JavaScript code I'm passing it as a string:
在 JavaScript 代码中,我将它作为字符串传递:
$.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:
最后我只是这样Split
的元素:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Method(string elements)
{
IList<long> selected = elements.Split<long>(',');
...
}
回答by Hero
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',
});