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

时间:2019-05-15 13:32:36

标签: c# json ajax .net-core

我正在尝试使用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; }
    }

我认为我距离还很遥远。我想念什么?谢谢。

2 个答案:

答案 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) {
            }
        });

应该工作