使用 ajax 我想传递 2 个对象:string[]和Options我的控制器。问题是每次string[]在控制器范围内都设置为null.
那是js代码:
$("#exportCsv").click(function () {
var checkboxes = $('.TableChBox:checkbox:checked');
var allIds = [];
for (var i = 0, n = checkboxes.length; i < n; ++i) {
var el = checkboxes[i];
if (el.id) {
allIds.push(el.id);
}
}
console.log(allIds); // it prints ["RId1604678", "RId1604679"]
var form = $('#SearchForm').serialize();
$.ajax({
url: '@Url.Action("ExportToCsv", "Bank")',
type: 'POST',
data: JSON.stringify({
ids: allIds,
options: form
}),
dataType: 'json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
async: true,
});
});
这就是 C# 代码:
public void ExportToCsv(string[] ids, Options options)
{
// ids is null here
// options is not null
}
当我使用调试器时,我可以看到,它options已成功填充,但ids为空。为什么会这样?
编辑 1
正如有人建议我应该添加contentType. 所以我补充说:
url: '@Url.Action("ExportToCsv", "Bank")',
type: 'POST',
contentType: "application/json; charset=utf-8",
仍然 -ids不是空的,而是options。
编辑 2
有人建议将函数中的两个参数更改为一个。所以我将代码更改为:
控制器的一部分
public class ExportModel
{
[JsonProperty(PropertyName = "one")]
public string One { get; set; }
[JsonProperty(PropertyName = "two")]
public string Two { get; set; }
}
[System.Web.Mvc.HttpPost]
public void ExportToCsv([System.Web.Http.FromBody] ExportModel model)
{
//model.One is null
//model.Two is null
}
部分js代码
data: JSON.stringify({
one: "foo",
two: "bar"
}),
即使使用带有两个字符串的简单示例,它也无法正常工作。
相关分类