Search code examples
javascriptc#asp.net-corerazor-pages

ASP.NET Razor Pages, passing data from the front-end script to the back-end


I am working on a project where I am using a map and need to send feedback to the backend with the current zoom level. The problem is that the page only returns a 400 Bad Request error along with "Error: SyntaxError: Unexpected end of JSON input."

.cshtml:

map.on('zoomend', function () {
    var zoomLevel = map.getZoom();

    // Enviar el nivel de zoom al backend
    fetch('@Url.Page("/Map", "UpdateZoom")', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(zoomLevel)
    })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error('Error:', error));
});

.cs:

public IActionResult OnPostUpdateZoom([FromBody] string zoom)
{
    ZoomLevel = JsonSerializer.Deserialize<int>(zoom);

    int valorCapturado = ZoomLevel;


    return new JsonResult(new { success = true, receivedValue = valorCapturado });
}

Upon inspection with breakpoints, I realized that the OnPostUpdateZoom method in the backend is never being triggered. I have also verified that @Url.Page("/Map", "UpdateZoom") is generating the correct URL.


Solution

  • You haven't included the AntiForgeryToken in the Fetch request, which is why you get a 400 Bad Request status code. Since you are posting JSON data, you should send this value in the request header. Also, you need to generate the value to post.

    Add @Html.AntiForgeryToken() anywhere in the Razor page which will generate a hidden field named __RequestVerificationToken then add its value to the request header:

    fetch('@Url.Page("/Map", "UpdateZoom")', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'RequestVerificationToken' : document.querySelector('[name="__RequestVerificationToken"]').value
            },
            body: JSON.stringify(zoomLevel)
        })
            .then(response => response.json())
            .then(data => console.log(data))
            .catch(error => console.error('Error:', error));
    

    https://www.learnrazorpages.com/security/request-verification#ajax-post-requests-and-json