【发布时间】:2019-08-02 19:12:44
【问题描述】:
作为 ASP.NET Core Razor Pages (Visual C#) 项目的一部分,我有一个用于执行 AJAX 请求的 JavaScript/jQuery 函数。 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',并将处理程序方法的名称从OnGetConditionalDropDown更改为OnPostConditionalDropDown,但请求总是失败。
我已将 @Html.AntiForgeryToken() 添加到发送 AJAX 请求的页面 (.cshtml),但我不确定它是否在正确的位置。目前,我将它放在调用 AJAX 请求的表单的 <form> 标记中。
我认为我在设置请求的方式上遗漏了一些东西,但我不知道它是什么。非常感谢任何帮助。
【问题讨论】:
标签: javascript jquery ajax asp.net-core razor-pages