Search code examples
javascriptc#ajaxasp.net-mvchttp-put

Receiving object properties are null on server after an ajax put request


I've a problem with sending data form the browser to an API on my server by an ajax request to the server (method is PUT). Here is my JavaScript code:

var json = JSON.stringify({
    StemType: {
        ID: parseInt(this.dataset.id),
        Type: this.dataset.type,
        GebruikerID: "@(Model.DeTopic.Gebruiker.Id)"
    },
    Punten: parseInt(this.dataset.punten),
    GestemdeGebruikerID: "@(Model.AangemeldeGebruiker)"
});

$.ajax({
    url: "../Stem/Toevoegen",
    type: "PUT",
    data: json,
    success: function (returnData) {
        // my code
    }
});

This is the json code in the variable json:

{
    "StemType": {
        "ID": 24731,
        "Type": "Topic",
        "GebruikerID": "539e6078"
    },
    "Punten": 1,
    "GestemdeGebruikerID": "3aedefab"
}

And here is the C# code on the server.

public class StemController : ApiController
{
    [HttpPost]
    [Authorize]
    [Route("Stem/Toevoegen")]
    public void Toevoegen([FromBody]Stem stem)
    {
        Console.WriteLine(stem.ToString());
    }
}

Here is the class Stem:

public class Stem
{
    public StemType StemType { get; set; }
    public int Punten { get; set; }
    public string GestemdeGebruikerID { get; set; }
}

public class StemType
{
    public int ID { get; set; }
    public Type Type { get; set; }
    public string GebruikerID { get; set; }
}

But if I debug my code on the server, I've got this:

StemType value is null, punten value is zero, GestemdeGerbuikerID is also null

Can anyone help me?


Solution

  • I've found two possible ways:

    1. Don't stringify it for send as an object.
    2. Add contentType: "application/json" for Json code.