我正在尝试使用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; }
}
我认为我距离还很遥远。我想念什么?谢谢。
答案 0 :(得分:1)
您需要使用内部带有列表的ViewModel:
public class YourViewModel
{
public List<FilterJSONItem> FilterJSON{ get; set; }
}
public class FilterJSONItem
{
public string FilterType { get; set; }
public string FilterDescription { get; set; }
public string OptionDescription { get; set; }
public bool OptionSelected { get; set; }
}
public ActionResult Method([FromBody]YourViewModel vm)
{
}
答案 1 :(得分:1)
[HttpPost]
public IActionResult Index([FromBody]FilterJSON[] filters)
{
//...code here...
return null;
}
和
$.ajax({
type: 'POST',
url: '@Url.Action("Index", "Home")',
data: JSON.stringify(filters),
contentType: "application/json; charset=utf-8",
success: function (view) {
},
failure: function (response) {
}
});
应该工作