我有一个看似简单的jQuery ajax函数来将一个整数数组发布到一个Web服务:
$(document).ready(function() {
$("#testButton").click(function() {
$.ajax({
type: "POST",
url: "api/setactivedemodatasetids/",
data: [1, 2, 8, 9],
success: function() {},
dataType: "application/json"
});
});
});
一个简单的ASP.Net Web API 2控制器,用于接收发布的数据:
[Route("api/setactivedemodatasetids/")]
[AcceptVerbs("POST")]
public void SetActiveDemoDataSetIds(int[] ids)
{
var db = new DataClassesDataContext();
// Do stuff
db.SubmitChanges();
}
当我在控制器中设置断点时,参数ids
的值为
{int[0]}
为什么呢?为什么它不是一个包含四个整数1,2,8和9的数组?
答案 0 :(得分:3)
设置dataType: "json"
设置contentType: "application/json; charset=utf-8"
和数据:JSON.stringify([1, 2, 8, 9] )
https://api.jquery.com/jQuery.ajax/
我认为此代码可以解决您的问题
$("#testButton").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "api/setactivedemodatasetids/",
data: JSON.stringify([1, 2, 8, 9]),
success: function () { },
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
//alert(xhr.responseText);
alert(thrownError);
}
});
});