【发布时间】:2019-05-15 13:32:36
【问题描述】:
我正在尝试使用 AJAX 将一组对象从我的视图传递到控制器。数组未传递给控制器(控制器操作接收 null)。
查看:
function submitFilters() {
var filters = [];
$(".filter-option-checkbox").each( function(){
var filter =
{
FilterType: $(this).find("#filter_Type").val().toString(),
FilterDescription: $(this).find("#filter_Description").val().toString(),
OptionDescription: $(this).find("#option_Description").val().toString(),
OptionSelected: $(this).find(".custom-control-input").prop('checked')
};
filters.push(filter);
});
$.ajax({
type: 'POST',
url: '@Url.Action("Index", "Category")',
data: JSON.stringify(filters),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (view) {
},
failure: function (response) {
}
});
}
控制器:
[HttpPost]
public IActionResult Index(FilterJSON[] filters)
{
//...code here...
}
对象类:
public class FilterJSON
{
public string FilterType { get; set; }
public string FilterDescription { get; set; }
public string OptionDescription { get; set; }
public bool OptionSelected { get; set; }
}
我不认为我离得很远。我错过了什么?谢谢。
【问题讨论】:
-
在 ajax 调用中不应该是 dataType: "json" 而不是 contenttype 吗?如果您使用 contenttype,我想它应该是“contentType”。我建议您检查您的 Http 请求。默认的 jquery.ajax() 内容类型是“pplication/x-www-form-urlencoded; charset=UTF-8”。我认为由于拼写错误,您仍然没有发送“应用程序/json”。
-
感谢您指出 dataType/contentType 问题。我会在问题中纠正这一点。
-
对不起我的错误:您不需要dataType作为它来将接收数据转换为指定格式。但我仍然建议您检查内容类型为application/json的http头。