Lucas Garcia
Lucas Garcia

Reputation: 207

Controller is geting an empty object when receiving ajax post request from javascript

I'm creating a react javascript component which gathers information from the user and sends a post request to an url endpoint using ajax. My component is reaching the endpoint. Here's the codes exemplifying my problem:

C# endpoint - Controller:

[EnhancedRequireHttps]
    [HttpPost]
    public ActionResult MyMethod(MyObject myObject)
    {...}

The object which I'm expecting:

public class MyObject
{
    public string Name;
    public string Number;
    public long Id;
    public int Code;
}

javascript data:

this.props.newValues = {
    Name : "John",
    Number : "1234567890",
    Id : "1234",
    Code : 1
}

javascript ajax request:

$.ajax({
        type: "POST",
        url: this.props.endpointurl, // Contains the endpoint
        data: this.props.newValues,

        success: function(response) {
        }.bind(this),

        error: function(err) {
        }.bind(this)
    });

Previously, I had all the parameters as my MyMethod's input, like this:

[EnhancedRequireHttps]
    [HttpPost]
    public ActionResult MyMethod(string Name, string Number, long Id, int Code)
    {...}

and the post was working properly, but I'm trying to make a clean code, so I created a class to contain those attributes, and when I did so, my problem started.

I tried creating an object named myObject to contain my parameters in the js code. I also tried using $(this.props.newValues).serialize() or JSON.stringify(this.props.newValues), and dataType = "json" or contentType = "application/json".

Thanks for reading and helping, I'm here to clear any doubt regarding my situation. :)

Upvotes: 2

Views: 855

Answers (1)

Eldarien
Eldarien

Reputation: 813

You need to specify contentType and send json as a string. See comments:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8", // Try to add this
    url: this.props.endpointurl,
    data: JSON.stringify(this.props.newValues), // And this

    success: function(response) {
    }.bind(this),

    error: function(err) {
    }.bind(this)
});

Upvotes: 1

Related Questions