无法使用带有ASP.NET Core和Entity Framework Core的Ajax发送数组数据

问题描述 投票:0回答:2

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

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]标记,但是它也不起作用!

帮助我解决此问题

asp.net-mvc asp.net-core entity-framework-core asp.net-core-2.0
2个回答
0
投票

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

将您的代码更改为

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

应该是对象而不是字符串


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

$.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中的[data:{ pendingTestResult: tests }与运行中的参数名称匹配并删除contentType设置。
© www.soinside.com 2019 - 2024. All rights reserved.