I am trying to send data from a page to the page model using AJAX (fetch API) POST request. I am able to reach the "OnPostTest" handler, but the variable "json" is null. Where could the issue be? Is it with my AJAX call or in the Razor page model method? Thank you.
Razor Page - Page Model
public JsonResult OnPostTest(string json)
{
return new JsonResult(json);
}
JavaScript
async function getData() {
fetch('./test/Test',
{
method: "POST",
body: JSON.stringify({
json: 'yourValue'
}),
headers: {
'X-CSRF-TOKEN': document.getElementsByName("__RequestVerificationToken")[0].value,
'Content-Type': 'application/json',
Accept: 'application/json',
}
})
.then(function (res) { return res.json(); })
.then(function (data) { alert((data)) })
}
Razor Page
<form method="post">
<button type="button" onclick="getData(this)" value="1">send</button>
</form>
----Edit----
JavaScript
async function getData() {
fetch('./test/Test',
{
method: "POST",
body: JSON.stringify(
{
name: "myname",
value: 1,
date:new Date()
}
),
headers: {
'X-CSRF-TOKEN': document.getElementsByName("__RequestVerificationToken")[0].value,
'Content-Type': 'application/json',
'Accept': 'application/json',
}
})
.then(function (res) { return res.json(); })
.then(function (data) { alert((data)) })
}
Razor Page - Page Model
public JsonResult OnPostTest([FromBody] ViewModel json)
{
return new JsonResult(json.Name);
}
public class ViewModel
{
public string Name { get; set; }
public int Value { get; set; }
public DateTime date { get; set; }
}