我发现在一个页面上有多个处理程序以及相关的命名约定(即 OnPostXXX)和“asp-post-hanlder”标签助手的示例。但是我怎样才能从 AJAX 调用中调用这些方法之一。
我有一个带有典型 MVC 视图和控制器的较旧示例,但这如何与 Razor 页面一起使用?
例如,如果我使用基本应用程序并将 About.cshtml 页面修改为以下内容:
@page
@model AboutModel
@{
ViewData["Title"] = "About";
}
<h2>@ViewData["Title"]</h2>
<h3>@Model.Message</h3>
<input type="button" value="Ajax test" class="btn btn-default" onclick="ajaxTest();" />
@section Scripts {
<script type="text/javascript">
function ajaxTest() {
console.log("Entered method");
$.ajax({
type: "POST",
url: '/About', // <-- Where should this point?
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, errorThrown) {
var err = "Status: " + status + " " + errorThrown;
console.log(err);
}
}).done(function (data) {
console.log(data.result);
})
}
</script>
}
并在模型页面 About.cshtml.cs
public class AboutModel : PageModel
{
public string Message { get; set; }
public void OnGet()
{
Message = "Your application description page.";
}
public IActionResult OnPost() {
//throw new Exception("stop");
return new JsonResult("");
}
}
OnPost 不是从 Ajax 调用中调用的。