我无法使用 Entity Framework Core 和 Ajax 将数据存储到数据库中

Posted

技术标签:

【中文标题】我无法使用 Entity Framework Core 和 Ajax 将数据存储到数据库中【英文标题】:I am unable to store data into database using Entity Framework Core and Ajax 【发布时间】:2020-07-21 15:01:26 【问题描述】:

我的代码有问题。问题是我没有使用 ajax 通过参数获取发布数据。

谁能解决这个问题?代码如下所示。

这是我通过 post 方法向控制器发送数据的 javascript 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),
            headers:  "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() ,
            success: function (data) 
                alert(data);
            ,
            error: function (e) 
                alert('Error' + JSON.stringify(e));
            
    );

这是控制器:

[HttpPost]
public async Task<IActionResult> SavePendingTest(List<PendingTestResult> pendingTestResult)

    if (ModelState.IsValid)
    
        foreach (PendingTestResult ptr in pendingTestResult)
        
            _db.Add(ptr);
            await _db.SaveChangesAsync();
        

        return RedirectToAction(nameof(Index));
    

    return View();

这是模型类:

public class PendingTestResult

    [Key]
    public int Id  get; set; 
    [Display(Name = "Patient Id")]
    public int PatientId  get; set; 

    [Display(Name = "Test Id")]
    public int TestId  get; set; 

    [Display(Name = "Test Parameter")]
    public int TestParameterId  get; set; 
    public string TestValue  get; set; 

    [Display(Name = "Test")]
    [ForeignKey("TestId")]
    //relation of Tests table
    public virtual Tests Tests  get; set; 

    [Display(Name = "Patient")]
    [ForeignKey("PatientId")]
    //relation of Patient table
    public virtual Patient Patient  get; set; 

    [Display(Name = "Test Parameter")]
    [ForeignKey("TestId")]
    //relation of Patient table
    public virtual TestParameter TestParameter  get; set; 

这是风景

@model DeltaSoftLIS.Models.Patient_Tests_TestParameter


@
    ViewData["Title"] = "Test Result";
    Layout = "~/Views/Shared/_Layout.cshtml";


<div class="container-fluid">
    <div class="row">
        <div class="col-md-3">
            <div class="card">
                <partial name="_SidebarMenuPartialReception" />
            </div>
        </div>
        <div class="col-md-9 animated bounce">
            <div class="card" style="padding:20px 50px;">
                <div class="row">
                    <div class="col-md-6">
                        <h2 class="text-info">Test Result</h2>
                    </div>
                </div>
                <br />

                <div class="row blue-gradient mb-4">
                    <div class="col-md-3">
                        <form asp-action="TestResult" method="post" class="form-inline">
                            <div class="form-group">
                                <label class="text-white">Visit Number &nbsp;</label>
                                <input type="text" class="form-control" id="visitNo" asp-for="patient.VisitNo" />
                                <input type="submit" value="Submit" class="btn blue-gradient" />
                            </div>
                        </form>
                    </div>
                </div>
                @if (ViewBag.error != null)
                
                    <div class="alert alert-danger">@ViewBag.error</div>
                
                else
                
                    <div class="container">
                        <div class="row">

                            @if (Model != null)
                            
                                <div class="col-md-2">
                                    Visit No: <span id="patinet.visitNo">@Model.patient.VisitNo</span>
                                </div>
                                <div class="col-md-4">
                                    Patient Name: <span style="text-transform:capitalize" class="patientId" id="@Model.patient.Id">@Model.patient.FirstName @Model.patient.MiddleName @Model.patient.LastName</span>
                                </div>
                            
                        </div>
                    </div>
                    @if (ViewBag.test != null)
                    
                        <div class="container p-4">
                            <form>
                            <table class="table table-bordered table-sm" style="height:auto">
                                <tr class="blue-gradient-rgba text-white">
                                    <th>Test Name</th>
                                    <th>Value</th>
                                    <th>Unit</th>
                                    <th>Normal</th>
                                    <th>Minimum</th>
                                    <th>Maximum</th>
                                </tr>
                                 @string testgroup = "";
                                     

                                     @foreach (var data in ViewBag.test)
                                     
                                        <tr>
                                            @if (testgroup != data.Tests.TestName)
                                            
                                                <input type="hidden" class="tid" value="@data.Tests.Id" />
                                                <th colspan="2">@data.Tests.TestName</th>

                                            
                                            @testgroup = data.Tests.TestName;
                                            
                                        </tr>
                                        @foreach (var tp in ViewBag.testPara)
                                        
                                            if (data.Tests.Id == tp.TestId)
                                            
                                                <tr>
                                                    <td>@tp.ParameterName</td>
                                                    <td><input type="hidden" class="tpId" value="@tp.Id"><input type="text" class="result"></td>
                                                    <td>@tp.Unit</td>
                                                    <td>@tp.NormalRange</td>
                                                    <td>@tp.Minimum</td>
                                                    <td>@tp.Maximum</td>
                                                </tr>
                                            
                                        
                                    
                                

                            </table>
                            </form>
                        </div>
                    

                
                <div class="row">
     
                    <div class="col-md-12 text-right">
                        @*@Html.ActionLink("Print Receipt", "printReceipt", new  id = Model.Id ,new  taget = "_blank" ) |*@

                        <a asp-action="Index">Back to List</a> |
                        <input type="button" value="Pending" id="pending" class="btn sunny-morning-gradient text-white" />
                        <input type="button" value="Complete" id="complete" class="btn blue-gradient" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () 
        $('.result').keyup(function () 
            var value = $(this).val();
            var min = parseFloat($(this).closest('tr').find("td:eq(4)").text());
            var max = parseFloat($(this).closest('tr').find("td:eq(5)").text());
            if (value < min) 
                $('.result').css( 'color': 'blue' )
            
            else if (value > max) 
                $('.result').css( 'color': 'red' )
            
            else 
                $('.result').css( 'color': 'green' )
            
        );

        $('#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));
                
            );
        
    );
</script>

请帮我解决这个问题并将列表保存到数据库中

控制台日志中的错误: 错误"readyState":4,"responseText":"System.InvalidOperationException: 未找到视图“SavePendingTest”。搜索了以下位置:\r\n/Areas/Reception/Views/PatientTests/SavePendingTest.cshtml\r \n/Areas/Reception/Views/Shared/SavePendingTest.cshtml\r\n/Views/Shared/SavePendingTest.cshtml\r\n/Pages/Shared/SavePendingTest.cshtml\r\n 在 Microsoft.AspNetCore.Mvc.ViewEngines .ViewEngineResult.EnsureSuccessful(IEnumerable`1 originalLocations)\r\n 在 Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext 上下文,ViewResult 结果)\r\n 在 Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext 上下文)\r\n 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker 调用程序,Task lastTask,State next,Scope 范围,Object state,Boolean isCompleted)\r\n 在 Microsoft。 AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed 上下文)\r\n 在 Microso ft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()\r\ n--- 从先前引发异常的位置结束堆栈跟踪 ---\r\n 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker 调用程序,任务 lastTask,下一个状态,作用域范围,对象state, Boolean isCompleted)\r\n 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)\r\n 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state , Boolean& isCompleted)\r\n 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()\r\n--- 从以前引发异常的位置结束堆栈跟踪 ---\r\n 在 Microsoft。 AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(资源eInvoker 调用程序)\r\n 在 Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端点端点、任务 requestTask、ILogger 记录器)\r\n 在 Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext 上下文)\r\ n 在 Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n 在 Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)\r\n 在 Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware。在 Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)\r\n 处调用(HttpContext httpContext)\r\n 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)\r\n\r\ nHEADERS\r\n=======\r\nAccept: /\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: en-US,en; q=0.9\r\n连接:关闭\r\n内容长度:351\r\n内容类型:应用通货膨胀/ JSON \ r \ nCookie:.AspNetCore.Antiforgery.N4je5mEcjHk = CfDJ8AIMWfGHX55FkS_e4YdMcbzY3x_6D6NUruknobs5IXFtvGUf98iczXoLcdV3uv0upJtPUqZsVfh1caiPUHsNj2Vd3ruV4MaiVmYVhItLdcLgp_MdoGjsQSz9kgTULqP-8VAt44Gei1H65bSR9M0eaTg \ r \ n主机:本地主机:44336 \ r \ nReferer:https://localhost:44336/Reception/PatientTests/TestResult \ r \ n用户代理:Mozilla的/ 5.0(Windows NT的10.0; WIN64; 64)为AppleWebKit / 537.36(KHTML,例如Gecko)铬/ 80.0.3987.163 Safari浏览器/ 537.36 \ r \ nrequestverificationtoken:CfDJ8AIMWfGHX55FkS_e4YdMcby-1dlSJss8EVbTOCIx1QPIjmq7HT5S65FLY_pNB67tGWoUF_1VICPa7tsrXvltyFQpalaUJrpQZcMbj_Yb5Ned8Q9Za3Teyq6FC8gCbk50v_NZj396PEQiVHpOMLrkxEk \ r \纳秒取-DEST:空\ r \ NX-请求-用:XMLHttpRequest的\ r \ norigin: https://localhost:44336\r\nsec-fetch-site: 同源\r\nsec-fetch-mode: cors\r\n","status":500,"statusText":"error"

【问题讨论】:

你看到了什么错误? 您在tests 中传递的数据是否正确?您可以使用console.log(tests) 在浏览器中查看数据。 发布请求是否到达服务器? 【参考方案1】:

添加contentType: "application/json"来指定你发送的数据类型。如果你不指定它,默认使用application/x-www-form-urlencoded; charset=UTF-8

 $.ajax(
        contentType: "application/json",           
);

并将[FromBody] 添加到您的操作中:

[HttpPost]
public async Task<IActionResult> SavePendingTest([FromBody]List<PendingTestResult> pendingTestResult)

    //...

更新

型号:

public class Patient_Tests_TestParameter

    public Patient patient  get; set; 

public class PendingTestResult

    [Key]
    public int Id  get; set; 
    [Display(Name = "Patient Id")]
    public int PatientId  get; set; 

    [Display(Name = "Test Id")]
    public int TestId  get; set; 

    [Display(Name = "Test Parameter")]
    public int TestParameterId  get; set; 
    public string TestValue  get; set; 

    [Display(Name = "Test")]
    [ForeignKey("TestId")]
    //relation of Tests table
    public virtual Tests Tests  get; set; 

    [Display(Name = "Patient")]
    [ForeignKey("PatientId")]
    //relation of Patient table
    public virtual Patient Patient  get; set; 

    [Display(Name = "Test Parameter")]
    [ForeignKey("TestId")]
    //relation of Patient table
    public virtual TestParameter TestParameter  get; set; 


public class TestParameter

    public int Id  get; set; 
    public int TestId  get; set; 
    public Test Test  get; set; 
    public int PatientId  get; set; 
    public Patient Patient  get; set; 
    public string ParameterName  get; set; 


public class Patient

    public int Id  get; set; 
    public string FirstName  get; set; 
    public string MiddleName  get; set; 
    public string LastName  get; set; 
    public List<TestParameter> TestParameter  get; set; 


public class Tests

    public int Id  get; set; 
    public string TestName  get; set; 
    public List<TestParameter> TestParameter  get; set; 


查看:

@model Patient_Tests_TestParameter

<div class="container-fluid">
    <div class="row">
        <div class="col-md-9 animated bounce">
            <div class="card" style="padding:20px 50px;">
                <div class="row">
                    <div class="col-md-6">
                        <h2 class="text-info">Test Result</h2>
                    </div>
                </div>
                <br />

                @if (ViewBag.error != null)
                
                    <div class="alert alert-danger">@ViewBag.error</div>
                
                else
                
                    <div class="container">
                        <div class="row">

                            @if (Model != null)
                            
                                <div class="col-md-4">
                                    Patient Name: <span style="text-transform:capitalize" class="patientId" id="@Model.patient.Id">@Model.patient.FirstName @Model.patient.MiddleName @Model.patient.LastName</span>
                                </div>
                            
                        </div>
                    </div>
                    @if (ViewBag.test != null)
                    
                        <div class="container p-4">
                            <form>
                                <table class="table table-bordered table-sm" style="height:auto">
                                    <tr class="blue-gradient-rgba text-white">
                                        <th>Test Name</th>
                                        <th>Value</th>
                                    </tr>
                                    @string testgroup = "";
                                    

                                    @foreach (var data in ViewBag.test)
                                    
                                        <tr>
                                            @if (testgroup != data.Tests.TestName)
                                            
                                                <input type="hidden" class="tid" value="@data.Tests.Id" />
                                                <th colspan="2">@data.Tests.TestName</th>

                                            
                                            @testgroup = data.Tests.TestName;
                                            
                                        </tr>
                                        @foreach (var tp in ViewBag.testPara)
                                        
                                            if (data.Tests.Id == tp.TestId)
                                            
                                                <tr>
                                                    <td>@tp.ParameterName</td>
                                                    <td><input type="hidden" class="tpId" value="@tp.Id">
                                                        <input type="text" class="result">
                                                    </td>
                                                </tr>
                                            
                                        
                                    


                                </table>
                            </form>
                        </div>
                    

                
                <div class="row">

                    <div class="col-md-12 text-right">
                        @*@Html.ActionLink("Print Receipt", "printReceipt", new  id = Model.Id ,new  taget = "_blank" ) |*@

                        <a asp-action="Index">Back to List</a> |
                        <input type="button" value="Pending" id="pending" class="btn sunny-morning-gradient text-white" />
                        <input type="button" value="Complete" id="complete" class="btn blue-gradient" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts

    <script>
        $(document).ready(function () 


            $('#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));
                    
                );
            
        );
    </script>

行动:

public IActionResult Index()

    var model = new Patient_Tests_TestParameter()
    
        patient = new Patient()
        
            Id = 1,
            FirstName = "Patient1",
            LastName = "PatientLast",
            MiddleName = "PationtMiddle"
        
    ;
    ViewBag.test = new List<PendingTestResult>()
    
        new PendingTestResult()  Tests = new Tests()  Id=1, TestName="test1" ,
        new PendingTestResult()  Tests = new Tests()  Id=2, TestName="test2" ,
        new PendingTestResult()  Tests = new Tests()  Id=3, TestName="test3" 
    ;
    ViewBag.testPara = new List<TestParameter>()
    
        new TestParameter() Id=1, TestId=1, ParameterName="Para1",
        new TestParameter() Id=2, TestId=1, ParameterName="Para2",
        new TestParameter() Id=3, TestId=2, ParameterName="Para3",
    ;
    return View(model);

结果:

更新 2:

[HttpPost]
[Route("Reception/PatientTests/SavePendingTest")]
public async Task<IActionResult> SavePendingTest([FromBody]List<PendingTestResult> pendingTestResult)

    if (ModelState.IsValid)
    
        foreach (PendingTestResult ptr in pendingTestResult)
        
            _db.Add(ptr);
            await _db.SaveChangesAsync();
        

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

    return new JsonResult("/Home/Privacy");

改变你的ajax成功函数:

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

【讨论】:

嗨,rena,感谢您的回答,但无法将数据输入控制器 你中招了吗?你能分享一下整个观点吗? 我添加到帖子请在上面找到。 我更新了整个代码。你确定你的tests 包含价值吗? i.stack.imgur.com/ELuyx.jpg 在应用您的代码后收到此错误

以上是关于我无法使用 Entity Framework Core 和 Ajax 将数据存储到数据库中的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 Entity Framework 5 在 SQLite 数据库中插入记录

我无法使用 Entity Framework Core 和 Ajax 将数据存储到数据库中

有没有办法以编程方式检查 Entity Framework Core 中的待定模型更改?

Entity Framework Core 2.1 无法更新具有关系的实体

System.Core 错误:使用 C# Entity Framework 和 Linq 和 Expression 的“代码应该无法访问”

Entity Framework 6 将存储过程添加到数据模型后无法构建