Home > Back-end >  json string on POST to MVC action method using AJAX is null
json string on POST to MVC action method using AJAX is null

Time:01-23

I am getting a hard time to find out why the string sent via AJAX request is null. Console.WriteLine(data) shows empty. Status is 200 OK. If I add some code to parse the string received, I get an error stating that JObject.Parse cannot be null. I don't know what am I missing. The javascript code is ok. The action method also seems ok, but my knowledge on Asp.Net Core and MVC is very scarce, so I am not sure. Can someone please point out what am I missing?

The javascript code:


    let obj = {email: email_address.value};
    let objStringified = JSON.stringify(obj);
    $.ajax({
       type: 'POST',
       contentType: 'application/json; charset=UTF-8',
       data: objStringified,
       url: '@Url.Action("ReturnCheckAccountDuplication")',
       dataType: 'text',
       success: function(data) {
          console.log(data);
       },
       error: function(error) {
          console.log("Keep trying", error);
       }
    });

C# code:

[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] string data)
{
   Console.WriteLine(data);
   JObject jObject = JObject.Parse(data);
   string email = (string)jObject["email"];
   bool emailExists = CheckAccountDuplication.Get(email);
   string returnResult = emailExists.ToString();
   return Content(returnResult);
}

CodePudding user response:

The easiest solution is to create a model representing the JSON data that your controller will receive. For example, create a class like so:

public class AccountCheckModel
{
    public string email { get; set }
}

Then, use it as the parameter for your controller method:

public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)

This is the preferred way to access the request body. To get the request body as a string, you have to jump through some serious hoops.

CodePudding user response:

An alternative way to send your data via AJAX to your Controller:

var json = {
       email: email_address.value
};

$.ajax({
   type: 'POST',
   data: {'json': JSON.stringify(json)},
   url: '@Url.Action("ReturnCheckAccountDuplication")',
   dataType: 'json',
   success: function(data) {
      console.log(data);
   },
   error: function(error) {
      console.log("Keep trying", error);
   }
});

And your Controller:

[HttpPost]
public ActionResult ReturnCheckAccountDuplication(string json)
{
   Console.WriteLine(json);
   JObject jObject = JObject.Parse(json);
   string email = (string)jObject["email"];
   bool emailExists = CheckAccountDuplication.Get(email);
   string returnResult = emailExists.ToString();
   return Content(returnResult);
}
  •  Tags:  
  • Related