I have a JavaScript/jQuery function used to execute AJAX requests as part of a ASP.NET Core Razor Pages (Visual C#) project. The AJAX request calls an "OnGet" handler method in the PageModel (.cshtml.cs) of whichever page it gets called on. AJAX request JS/jQuery:
function conditionalDropDown(parameters) {
//code to get handler method inputs in correct format
var pathname = window.location.pathname;
var handler = "?handler=ConditionalDropDown";
var actionpath = pathname + handler;
$.ajax({
dataType: 'json',
url: actionpath,
type: 'GET',
data: {
parameterName: parameterValue
},
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
//dealing with the data returned by the request
},
error: function () {
alert("AJAX Request Failed, Contact Support");
}
});
}
Handler Method in PageModel:
public JsonResult OnGetConditionalDropDown(parameters)
{
//call a function to get the return string
return new JsonResult(dropdownHTML);
}
I want to change my AJAX request such that it uses an "OnPost" handler method instead. I have tried changing type: 'GET'
to type: 'POST'
in the AJAX request function, and the name of the handler method from OnGetConditionalDropDown
to OnPostConditionalDropDown
but the request always fails.
I have @Html.AntiForgeryToken()
added to the page (.cshtml) from which the AJAX request is sent, but I'm not sure it's in the right place. Currently, I have it inside the <form>
tags of the form from which the AJAX requests are called.
I think I'm missing something in the way the request is set up, but I have no idea what it is. Any help is greatly appreciated.