简体   繁体   中英

Ajax Post (Model binded) passing null to the controller

I am making an AJAX POST request to the controller (ASP.NET Core MVC), yet the value for the parameter is coming through as null. I tried several solutions given on StackOverflow. But, I couldn't correct it. Please help.

My view collects class fees information. There may have more than one payment.

$(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)
{
---
}

Object details at runtime 在此处输入图像描述

From your attached screenshot for data to be passed to the controller, the data's structure was unmatched with the data model the controller expected.

Assume the data structure for the front-end is correct .

Controller should expect that the received data is a StudentPaymentSlipVM object . While in the StudentPaymentSlipVM object, the fees is a StudentPaymentPaidClassVM array .

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()
};

I tried to pass my data to controller by binding to a ViewModel (StudentPaymentSlipVM) which has all required definitions. But I couldn't do it. So I changed the way and pass my object to Controller as following way now it is working. And also I would like to thanks Yong Shun.

  1. Changed the JQuery code
 $.ajax({
                     type: 'POST',
                     url: '@Url.Action("action", "controller")',                    
                     headers: { 'RequestVerificationToken': gettoken() },
                     data: dataObj,
                 })
  1. I changed the Controller
        [HttpPost]
        public ActionResult StudentPayment_Create(List<StudentPaymentPaidClassVM> Fees,  string Bank, decimal PaidAmount, DateTime PaidDate)
        {
.....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM