C# 如何使用AJAX将对象数组从视图传递到控制器

C# 如何使用AJAX将对象数组从视图传递到控制器,c#,json,ajax,.net-core,C#,Json,Ajax,.net Core,我试图用AJAX将一组对象从视图传递给控制器。数组未传递给控制器(控制器操作接收null) 视图: 控制器: [HttpPost] 公共IActionResult索引(FilterJSON[]过滤器) { //…代码在这里。。。 } 对象类: 公共类过滤器json { 公共字符串筛选器类型{get;set;} 公共字符串筛选器说明{get;set;} 公共字符串选项说明{get;set;} 公共布尔选项选择{get;set;} } 我想我已经不远了。我错过了什么?谢谢。您需要使用带有列表的

我试图用AJAX将一组对象从视图传递给控制器。数组未传递给控制器(控制器操作接收null)

视图: 控制器:
[HttpPost]
公共IActionResult索引(FilterJSON[]过滤器)
{ 
//…代码在这里。。。
}
对象类:
公共类过滤器json
{
公共字符串筛选器类型{get;set;}
公共字符串筛选器说明{get;set;}
公共字符串选项说明{get;set;}
公共布尔选项选择{get;set;}
}

我想我已经不远了。我错过了什么?谢谢。

您需要使用带有列表的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)
{
}
公共类YourViewModel
{
公共列表过滤器JSON{get;set;}
}
公共类过滤器
{
公共字符串筛选器类型{get;set;}
公共字符串筛选器说明{get;set;}
公共字符串选项说明{get;set;}
公共布尔选项选择{get;set;}
}
公共操作结果方法([FromBody]YourViewModel vm)
{
}


应该行得通

这很有道理。我已经实施了你的建议。但是,我仍然没有收到动作中的对象。我还需要以某种方式修改AJAX调用中的“数据”头吗?关于如何传递数据,有一些细节。我使用的是纯MVC方式,所以我的示例不会真正帮助您。有些人建议用户在签名中使用[FromBody],值得一试。您的代码中有一个错误。泛型列表类型应该是FilterJSONItem,至少在您的情况下是这样,但在OP的情况下不是这样。我已经编辑过了。在ajax调用中,它不应该是数据类型:“json”而不是contenttype吗?如果你使用contenttype,我想应该是“contenttype”。我建议您检查您的Http请求。默认的jquery.ajax()内容类型是“application/x-www-form-urlencoded;charset=UTF-8”。我认为由于输入错误,您仍然没有发送“application/json”。感谢您指出数据类型/内容类型问题。我会更正问题中的错误。对不起,我的错误是:您不需要将接收数据转换为指定格式的数据类型。但我仍然建议您检查http标头,确保内容类型为application/json。这样做了!谢谢我应该从一开始就包括[FromBody]。
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)
{
}
    [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) {
            }
        });