1
votes

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.

1

1 Answers

3
votes

Answering my own question...

  1. AJAX Request - removed beforeSend function in request, replaced with: headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() }, in request initialisation.
  2. AJAX Request - changed type: 'GET' to type: 'POST'
  3. Handler Method - OnGet --> OnPost
  4. Page .cshtml - removed @Html.AntiForgeryToken(), added method="post" to form from which AJAX request is made

Works perfectly now!