【发布时间】: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 </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)在浏览器中查看数据。 -
发布请求是否到达服务器?
标签: asp.net asp.net-core entity-framework-core asp.net-core-mvc asp.net-core-2.0