Sergio Di Fiore
Sergio Di Fiore

Reputation: 466

ASP.NET controller does not receiving data from Ajax POST call

I've been to basically all questions there were but seems I'm missing something pretty basic.

I have a simple class:

public class Recebe
{
    public string Name { get; set; }
    public string Email { get; set; }
}

A controller POST action:

[HttpPost]
public IActionResult ToggleLikeClicked(Recebe recebe)
{
    return Json("Retorno");
}

And an Ajax call:

$.ajax({
     type: 'POST',
     url: '/StartUps/ToggleLikeClicked',
     contentType: 'application/json',
     dataType: 'json',
     data: JSON.stringify({
          'Name': 'Sergio',
           'Email': '[email protected]'
     }),
     beforeSend: function () {
        console.log('Before send');
     },
     success: function (response) {
        console.log('success');
        console.log(response);
      },
      complete: function () {
         console.log('completed');
      },
      error: function (jqXHR, textStatus, errorThrown) {
          console.log('Status: ' + jqXHR.status + '; Error: ' + jqXHR.responseText);
      },
  });

From the browser console, I know the whole thing is executed, yet when debugging the "receive" is null.

What's wrong?

Upvotes: 2

Views: 861

Answers (1)

Lukas
Lukas

Reputation: 498

Try editing the JSON you are sending to:

{
    'name': 'Sergio',
    'email': '[email protected]'
}

You can also try adding the [FromBody] attribute to the parameter in the controller:

public IActionResult ToggleLikeClicked([FromBody] Recebe recebe)

Upvotes: 2

Related Questions