I have an issue with a simple jQuery $.post in my application. I have tried many methods and solutions on the internet to no avail. When post request is sent I see 400 error
public class RecoveryAdhocInvoicingModel : PageModel
{
Public IActionResult OnPostDoJob(string invNo, string account)
{
//var emailAddress = Request.Form["emailaddress"];
// do something with emailAddress
return new JsonResult("");
}
}
In my script the $.post method is called via button click:
$('#submitBtnUpdateJob').click(function (evt) {
var formdata = new FormData();
formdata.append("invNo", $('#adhocInvoiceNumber').val());
formdata.append("account", $('#invoiceAccountInput').val());
$.post(window.location.href '?handler=DoJob', JSON.stringify(formdata), function () {
alert('Posted');
});
});
CodePudding user response:
You need to add the RequestVerificationToken
header to the request.
$.ajax({
type: "POST",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
url: window.location.href '?handler=DoJob',
data: {
"invNo": $('#adhocInvoiceNumber').val(),
"account": $('#invoiceAccountInput').val()
},
contentType: "application/x-www-form-urlencoded"
}).done(function (response) {
alert('Posted');
});
Documentation: https://www.learnrazorpages.com/security/request-verification#ajax-post-requests-and-json