1

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: '[email protected]', 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

1
  • 2
    "I've tried setting up a class and receiving that" by that you mean you made a C# class with "name", "email", and "password" properties, then changed the CreateUser method to have only a parameter of that class type (with some arbitrary parameter name)? If you try it again, try adding [FromBody] before the parameter's type. Commented Feb 13, 2024 at 23:26

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.