Search code examples
c#.netajax.net-corerazor-pages

AJAX post data not parsed correctly


I'm having trouble posting data to my Razor Pages page handler using an AJAX post.

var $container = $('.railcars');
var $rows = $container.children('.row');
var sources = [];   //data = { storage = [], railcars = [] };
for (var i = 0; i < $rows.length; i++) {
    var $sourceType = $($rows[i]).find('.source-type input');
    sources.push({
        isStorage: $sourceType.prop('checked'),
        source: $($rows[i]).find('.source-number').val(),
        volume: 0,
        markAsEmpty: false });
}

$.ajax({
    type: 'POST',
    url: '?handler=CheckNegativeWeights',
    data: JSON.stringify(sources),
    headers: {
        "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()
    },
})
.done(function (response) {
    // ...
})
.fail(function (response) {
    // ...
})

My handler gets an empty collection.

enter image description here

I can see the data is there, but apparently it isn't in the correct format.

enter image description here

Can someone see what I'm missing.


Solution

  • You are serializing the data to JSON. Handler methods cannot parse that without some help. Specifically, you need to set the content type of the request to application/json, and tell the handler method that the data is in the body of the request using the [FromBody] attribute.

    $.ajax({
        type: 'POST',
        url: '?handler=CheckNegativeWeights',
        data: JSON.stringify(sources),
        contentType: "application/json",
        headers: {
            "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val()
        },
    })
    

    And

    public async Task<IActionResult>OnPostCheckNegativeWeights([FromBody]YourModel model)