Search code examples
javascriptc#asp.netajaxmodel-view-controller

AJAX Post returning NULL in Controller (ASP.NET MVC)


I've got a Javascript function, and I want it to pass through data to my controller.

This is my Javascript code:

    $.ajax({
        type: "POST",
        url: "/Home/CreateUser",
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({name: 'Dylan', email: 'an@email.com', password: 'password'}),
        success: function (response) {
            window.location.href = 'dashboard';
        },
        error: function (error) {
            alert('Error while signing up: ' + error);
        }
        })

..and this is how I've got my Controller set up to receive the request:

    [HttpPost]
    public ActionResult CreateUser(string name, string email, string password)
    {
        Console.WriteLine("Data received successfully: Name - " + name + ", Email - " + email + ", Password - " + password);
        return Content("Data received successfully: Name - " + name + ", Email - " + email + ", Password - " + password);
    }

Currently each value is passed through as null and I can't figure out why this isn't working. The request in the browser network tab appears to be sending the Json so I think there is something wrong with how I have set up my controller. I've tried setting up a class and receiving that, but that still won't work.

Thanks, Dylan


Solution

  • Use one of the following options:

    #1 - specify [FromBody]

    public ActionResult CreateUser([FromBody]string name, [FromBody]string email, [FromBody]string password)
    

    #2 - use [ApiController] attribute on your controller

    #3 - create a model for your payload

    public class RequestModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
    }
    

    then use it

    public ActionResult CreateUser([FromBody]RequestModel request)
    {
       Console.WriteLine($"Data received successfully: Name - {request.Name}, Email - {request.Email}, Password - {request.Password});
       ..
    }
    

    More info about Model Binding could be found here