我如何从 $.ajax 发送 int 数组到 c# mvc?
我如何从 $.ajax 发送 int 数组到 c# mvc?
$.ajax({
url: <Url of the action>,
type: "POST",
data: JSON.stringify([1,2,3]),
dataType: "json",
contentType: 'application/json; charset=utf-8'
});
并在动作中。
public ActionResult ReceiveIntArray(int[] ints)
{
...
}
MVC应该自动解析JSON。
请查看这个问题。
尝试使用这个问题中提供的解决方案:
Set the
traditional
property to true before making the get call. i.e.:
jQuery.ajaxSettings.traditional = true $.get('/controller/MyAction', { vals: arrayOfValues }, function (data) { ... }
input:hidden
元素来实现。<input type="hidden" name="elements" value='@String.Join(",", ViewBag.MyArray)' />
在 JavaScript 代码中,我将它作为字符串传递:
$.ajax({
type: "POST",
url: '/Controller/Method',
data:
{
recipients: $("input[name=elements]").val()
},
traditional: true,
success: updateSelected
});
拆分
元素:[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Method(string elements)
{
IList<long> selected = elements.Split<long>(',');
...
}
Sting.Split()
进行解析。$.get("/path-to/receiver/", { myArray: myArray.toString() } );
然后,在服务器上使用string[] stringArray = Request.QueryString["myArray"].ToString().Split(',')
将值提取到字符串数组中,然后使用Int32.TryParse
最终得到一个整数数组。
jQuery GET语法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',
});