[英]Ajax Post (Model binded) passing null to the controller
我正在向 controller(ASP.NET Core MVC)发出 AJAX POST 请求,但参数的值是 null。 我尝试了 StackOverflow 上给出的几种解决方案。 但是,我无法纠正它。 请帮忙。
我的观点收集 class 费用信息。 可能有不止一项付款。
$(function () {
$('#sendSlip').click(function (e) {
e.preventDefault();
let fees = new Array(); //To store payment info
let tb = $('#feesTable:eq(0) tbody');
//Collecting info of each payment
tb.find("tr").each(function () {
let row = $(this);
let fee = {};
if (row.find('input:checkbox:first').is(':checked')) {
fee.ClassId = row.find("TD").eq(0).html();
fee.FeeId = row.find("TD").eq(1).html();
fee.Amount = row.find(".fee").html();
fee.Month = row.find(".month").html();
fees.push(fee);
}
});
//Arranging data to send to controller
var data = {
fees: fees,
Bank: $(".bank").val(),
PaidAmount : $(".amount").val(),
PaidDate : $(".date").val()
};
console.log(data);
$.ajax({
type: 'POST',
url: '@Url.Action("StudentPayment_Create", "StudentPayment")',
contentType: "application/json",
headers: { 'RequestVerificationToken': gettoken() },
data: //{ data: JSON.stringify(data) },
JSON.stringify(data) ,
})
});
});
Model
public class StudentPaymentSlipVM
{
public StudentPaymentPaidClassVM fees { get; set; }
public string Bank { get; set; }
public DateTime PaidDate { get; set; }
public int PaidAmount { get; set; }
}
Controller
public ActionResult StudentPayment_Create([FromBody] List<StudentPaymentSlipVM> data)
{
---
}
从您附加的要传递到 controller 的数据的屏幕截图中,数据的结构与预期的 controller 的数据 model 不匹配。
假设前端的数据结构是正确的。
Controller 应该期望收到的数据是StudentPaymentSlipVM
object 。 在StudentPaymentSlipVM
object 中, fees
是StudentPaymentPaidClassVM
数组。
Model
public class StudentPaymentSlipVM
{
public List<StudentPaymentPaidClassVM> fees { get; set; }
public string Bank { get; set; }
public DateTime PaidDate { get; set; }
public int PaidAmount { get; set; }
}
Controller
public ActionResult StudentPayment_Create([FromBody] StudentPaymentSlipVM data)
{
}
While from your JQuery part, make sure that your data object to be passed to API must be matched with the data type as your model in the back-end.
var data = {
fees: fees,
Bank: $(".bank").val(),
PaidAmount : parseInt($(".amount").val()),
PaidDate : $(".date").val()
};
我试图通过绑定到具有所有必需定义的 ViewModel (StudentPaymentSlipVM) 将我的数据传递给 controller。 但我做不到。 所以我改变了方式并将我的 object 传递给 Controller 如下方式现在它正在工作。 我还要感谢永顺。
$.ajax({
type: 'POST',
url: '@Url.Action("action", "controller")',
headers: { 'RequestVerificationToken': gettoken() },
data: dataObj,
})
[HttpPost]
public ActionResult StudentPayment_Create(List<StudentPaymentPaidClassVM> Fees, string Bank, decimal PaidAmount, DateTime PaidDate)
{
.....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.