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

95
Visualizações
json string on POST to MVC action method using AJAX is null

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

The solution on the controller side is

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

[HttpPost]
public ActionResult ReturnCheckAccountDuplication([FromBody] AccountCheckModel data)
{
   string result = CheckAccountDuplication.Get(data.Email).ToString();
   return Content(result);
}

Thanks to all the members who commented on my problem, especially John Glenn who provided a solution. I had been trying for several days but without success. My knowledge of Asp.Net Core is very poor indeed. Thank you very much.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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