无法使用 ajax 和 asp.net core 发送数组

Ham*_*Ebr 4 asp.net arrays ajax jquery asp.net-core

我写了这个ajax函数:

$(function () {
        $("#showReport").click(function () {
            var data = [];
            for (var i = 0; i <@Model.LiFilters.Count;i++) {
                data[i] = $("#filter" + i).val();
                $("#myDiv").html("Hello!");
            }

            alert('{filters:' + JSON.stringify(data) + '}');
            $("#myDiv").remove();
            $.ajax({
                type: "POST",
                url: '@Url.Action("ShowReport", "Report")',
                traditional: true,
                //data: '{filters:' + JSON.stringify(data) + '}',
                data: { filters : data },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(data);
                    alert(response[0]);
                    $("#myDiv").html(response[0]);
                    alert(response);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
            return false;
        });
    });
Run Code Online (Sandbox Code Playgroud)

并在报告控制器中有此操作:

 [HttpPost]
public JsonResult ShowReport(string[] filters)
{
    C_AminReport aminReport = null;
    string sErr = string.Empty;
    //C_ReportParams aminParams = null;
    //C_AminReport aminReport;
    string sReport = "Empty Report!";
    if (C_AminReport.U_GetReport(aminReport.ID, out aminReport))
    {
        int iConIndex = Get_ServiceIndex();
        aminReport.U_RenderReport(iConIndex, ref sErr);
        aminReport.U_GetReportFromAmin(iConIndex, aminReport, out sReport, ref sErr);
    }
    string[] asReport;
    JsonBuilder.U_TryReadJson(sReport, out asReport);
    return Json(asReport);
}
Run Code Online (Sandbox Code Playgroud)

但是当运行代码时,我看到数据数组已填充,但在 ShowReport 操作内部,fillters 数组是一个空数组并且未填充!我还在操作参数中尝试了 [FromBody] 标签,但它不起作用!问题是什么?

Gab*_*uci 5

我测试了您的 JavaScript,它正在尝试发送查询字符串中的所有数据。

你必须使用JSON.stringify. 其中之一应该有效:

data: '{filters:' + JSON.stringify(data) + '}'
Run Code Online (Sandbox Code Playgroud)

或者

data: JSON.stringify(data)
Run Code Online (Sandbox Code Playgroud)

我怀疑第二个会起作用。

你可能还需要[FromBody]