【发布时间】:2019-09-02 22:32:22
【问题描述】:
在 Visual Studio 中 ASP.NET Core Razor Pages 项目的自动生成的 site.js 文件中,我尝试使用 Ajax 调用
$.ajax
({
type: "POST",
url: "",
data: "asdsad",
dataType: "text",
success: function (result) {
alert(result);
},
error: function (status, ex) {
alert("Error Code: Status: " + status + " Ex: " + ex);
}
});
一个 C# 函数。我的项目树如下所示:
builder.cshtml.cs 文件也是在我添加 builder.cshtml 页面时由 Visual Studio 自动生成的。在我的builder.cshtml.cs 里面有这个代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace MyProjectName.Pages
{
public class Index1Model : PageModel
{
public string Message { get; set; } = "Initial Request";
public void OnGet()
{
Message = "Test1";
}
public void HelloFunc()
{
Message = "BuilderJob";
}
}
}
我添加了函数HelloFunc() 和Message 变量。通过ASP.NET Core documentation by Microsoft 后,我不明白从我的Ajax 代码中调用HelloFunc 的“url”是什么。它不是/builder/HelloFunc(不起作用)。如何从我的 Ajax 调用中访问此 HelloFunc?
答案是将HelloFunc 更改为OnPostHelloFunc() 并使用此url: /builder?handler=HelloFunc,如果您只是测试而不使用验证令牌,请按照此处test .net core 2 page using Postman return 400 bad request 的说明插入[IgnoreAntiforgeryToken(Order = 1001)]
【问题讨论】:
-
void 方法没有返回
-
是由于旧代码,将其从问题中删除
-
查看this demo 以获得多个提交按钮。有两个示例,第一个使用标准表单,第二个使用 ajax,我认为这会对您有所帮助
标签: c# asp.net-core razor .net-core razor-pages