Home > Software engineering >  ASP.NET Core - posting form data to controller using ajax. One method works, one does not. Why?
ASP.NET Core - posting form data to controller using ajax. One method works, one does not. Why?

Time:08-12

I am posting data from a view, in simple HTML form

<form id="notificationForm" method="post">

Then, I am sending the form data to a controller (simplified example):

[HttpPost]
public JsonResult UpdateNotification(LenderNotificationEvent model)
{
   return Json("Ok");
}

I have tried 2 ways to get the form data to a model in the controller. This does not work:

$("#notificationForm").submit(function(e){
   e.preventDefault();
   var jqxhr = $.ajax({
      url: "/Lender/UpdateNotification",
      type: "POST",
      dataType: "json",
      data: $("#notificationForm").serialize(),
      contentType: "application/json; charset=utf-8"
      });

      jqxhr.done(function (data) {
      });

      jqxhr.fail(function () {
      });
    
});

This does work:

$("#notificationForm").submit(function(e){
  e.preventDefault();
  $.post('/Lender/UpdateNotification', $('#notificationForm').serialize(), function () {
});

Why? I don't understand how they are different.

EDIT: What I mean by "not working", the model is null when I use $.ajax and the model is filled with data using $.post. The controller gets hit by both methods.

EDIT 2: I have stepped through the code, I do not get errors, and when I use $.ajax the model object in the controller is empty, and when I use $.post, the model object in the controller is filled with expected data.

CodePudding user response:

I can see that you have a typo in the $.ajax() code:

  data: $("#notificationForm).serialize(),
  contentType: "application/json; charset=utf-8"
});

It's actually missing a double quote in form id, so it should be:

  data: $("#notificationForm").serialize(),
  contentType: "application/x-www-form-urlencoded; charset=utf-8"
});

Update: After fixing the typo try setting the contentType to application/x-www-form-urlencoded instead of application/json

  • Related