无法使用 ajax with ASP.NET Core 和 Entity Framework Core 发送数组数据

Unable to send array data using ajax with ASP.NET Core and Entity Framework Core

我正在尝试将数组发送到控制器,但它在控制器参数中为空。

Ajax函数为:

$('#pending').click(function () {
    SaveTestResult("/Reception/PatientTests/SavePendingTest");
});

function SaveTestResult(url) {
    var pid = $('.patientId').attr('id');
    var tid = "";
    var tval = "";
    var tpid = "";
    var tests = [];

    $("table > tbody > tr").each(function () {
         testId = $(this).find('.tid').val();

         if (typeof (testId) != "undefined") {
             tid = testId;
         }

         var rowText = ""

         $(this).find('td').each(function () {
             tpid = $(this).find('.tpId').val();
             tval = $(this).find('.result').val();

             if (typeof (tpid) != "undefined") {
                 tests.push({ PatientId: pid, TestId: tid, TestParameterId: tpid, TestValue: tval });
             }
         });
     });

     // alert(JSON.stringify(tests));
     $.ajax({
                type: "POST",
                url: url,
                data: JSON.stringify(tests),
                contentType: "application/json",
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                success: function (data) {
                    alert(data);
                },
                error: function (e) {
                    alert('Error' + JSON.stringify(e));
                }
    });
}

这是控制器方法:

[HttpPost]
[Route("Reception/PatientTests/SavePendingTest")]
public async Task<IActionResult> SavePendingTest(List<PendingTestResult> pendingTestResult)
{
    if (ModelState.IsValid)
    {
        foreach (PendingTestResult ptr in pendingTestResult)
        {
            _db.Add(ptr);
            await _db.SaveChangesAsync();
        }

        // return new JsonResult("Index");
    }

    return new JsonResult(pendingTestResult); ;
}

但是当 运行 代码我看到数据数组已填充但在 SavePendingTest 操作内部时,pendingTestResult 是空的且未填充!我也尝试了动作参数中的 [FromBody] 标签,但它也不起作用!

帮我解决这个问题

您发送的字符串没有名称,因此控制器无法获取值。

将您的代码更改为

$.ajax({
type:"POST",
url:url,
data:test
...
});

test 应该是 object 而不是 string.

您可以通过以下方式传递对象列表:

$.ajax({
    type: "POST",
    url: "Reception/PatientTests/SavePendingTest",
    data: { pendingTestResult: tests },

    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
    success: function (data) {
        alert(data);
    },
    error: function (e) {
        alert('Error' + JSON.stringify(e));
    }
});

pendingTestResult in data:{ pendingTestResult: tests } 匹配操作上的参数名称并删除 contentType 设置。