Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

248
Vistas
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 enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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()
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

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)
        {
.....
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda