skip to Main Content

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.

2

Answers


  1. map.getZoom() return a Number, I write an example to implement the front-end script to the back-end.I hope this helps you.

    1 MyModel.cs

        public class MyModel{public int Key { get; set; }}
    

    2 .cs

        public IActionResult OnPostUpdateZoom([FromBody] MyModel model)
            {
                 return new JsonResult(
                  new { success = true, receivedValue = model.Key });
            }
    

    3 .cshtml

        $(document).ready(function () {
           var zoomLevel = 12;
           var obj = { Key: zoomLevel }
        // Enviar el nivel de zoom al backend
          fetch("?handler=UpdateZoom", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(obj)
         })
                    
            .then(data => console.log(data))
            .catch(error => console.error('Error:', error));
        })
    

    The result is :

    enter image description here

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search