我的代码有问题。问题是我没有使用ajax按参数获取发布数据。
任何人都可以解决此问题吗?代码如下所示。
这是Javascript Ajax代码,我在其中通过post方法将数据发送到控制器:
$('#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; }
}
请帮助我解决此问题并将列表保存到数据库中
添加contentType: "application/json"
以指定要发送的数据类型。如果未指定,默认情况下它将使用application/x-www-form-urlencoded; charset=UTF-8
:
$.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));
}
});
并将[FromBody]
添加到您的操作中:
[HttpPost]
public async Task<IActionResult> SavePendingTest([FromBody]List<PendingTestResult> pendingTestResult)
{
//...
}