在Razor页面中使用OnPost页面处理程序进行AJAX请求

问题描述 投票:0回答:1

我有一个JavaScript / jQuery函数用于执行AJAX请求,作为ASP.NET Core Razor Pages(Visual C#)项目的一部分。 AJAX请求在PageModel(.cshtml.cs)中调用它所调用的任何页面的“OnGet”处理程序方法。 AJAX请求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");
    }
});
}

PageModel中的处理程序方法:

public JsonResult OnGetConditionalDropDown(parameters)
    {
        //call a function to get the return string

        return new JsonResult(dropdownHTML);
    }

我想更改我的AJAX请求,以便它使用“OnPost”处理程序方法。我已经尝试在AJAX请求函数中将type: 'GET'更改为type: 'POST',以及从OnGetConditionalDropDownOnPostConditionalDropDown的处理程序方法的名称,但请求总是失败。

我将@Html.AntiForgeryToken()添加到发送AJAX请求的页面(.cshtml)中,但我不确定它是否在正确的位置。目前,我将它放在调用AJAX请求的表单的<form>标记内。

我想我在设置请求的方式上遗漏了一些东西,但我不知道它是什么。任何帮助是极大的赞赏。

javascript jquery ajax asp.net-core razor-pages
1个回答
0
投票

回答我自己的问题......

  1. AJAX请求 - 在请求中删除了beforeSend函数,在请求初始化时替换为:headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
  2. AJAX请求 - 将type: 'GET'更改为type: 'POST'
  3. 处理程序方法 - OnGet - > OnPost
  4. 页面.cshtml - 删除了@Html.AntiForgeryToken(),添加了method="post"以形成AJAX请求

现在完美运作!

© www.soinside.com 2019 - 2024. All rights reserved.