无法使用带有asp.net核心实体框架核心的ajax发送数组数据

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

我正在尝试将数组发送到控制器,但在控制器参数中为空白。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
1个回答
0
投票

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

将您的代码更改为

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

应该是对象而不是字符串

© www.soinside.com 2019 - 2024. All rights reserved.