Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda