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
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
2 .cs
3 .cshtml
The result is :
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:https://www.learnrazorpages.com/security/request-verification#ajax-post-requests-and-json