ASP.NET Core Razor Pages 使用ajax get和post
2025-04-141. Razor Pages普通页面的跳转
使用 asp-page 属性进行页面跳转,例如:
<a asp-page="About">About</a> <form asp-page="./Index" method="get"> <div class="form-actions no-color"> <p> Find By Name: <input type="text" name="searchString" value="@Model.CurrentFilter" /> <input type="submit" value="Search" class="btn btn-primary" />| <a asp-page="./Index">Back to full list</a> </p> </div> </form>
注意:form 默认为 post 提交,而 asp-page 跳转的页面默认使用 get 方法(如 OnGetAsync 或 OnGet),如果同时存在可能会导致运行错误。
2. 针对一个页面的多个处理
可以在同一个页面中使用不同的处理方法,通过 asp-page-handler 指定处理器,例如:
<form method="POST"> <div>Name: <input asp-for="Customer.Name" /></div> <input type="submit" asp-page-handler="JoinList" value="Join" /> <input type="submit" asp-page-handler="JoinListUC" value="JOIN UC" /> </form>
这将分别调用 OnPostJoinListAsync 和 OnPostJoinListUCAsync 方法。
3. Razor Pages中ajax的Get使用
使用 jQuery 的 $.get 或 $.ajax 方法进行 GET 请求,例如:
$.get("?handler=Filter", { id: $(this).attr("data-id") }, function (result) { console.log(result); }); $.ajax({ type: 'GET', contentType: "application/json", dataType: "json", url: "?handler=Filter", success: function (result) { alert(result); } });
这将调用 OnGetFilterAsync 方法。注意:URL 中需要指定 handler 参数。
4. Razor Pages中ajax的Post使用
由于 Razor Pages 默认启用防伪验证(Anti-Forgery Token),直接使用 ajax 的 POST 请求可能会出错。
解决方法1(推荐):
在 Startup.cs 的 ConfigureServices 方法中添加:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
在页面中添加防伪令牌:
@Html.AntiForgeryToken()
在 ajax 请求中添加防伪令牌头:
$.ajax({ url: '?handler=Filter2', type: 'POST', contentType: 'application/json; charset=utf-8', headers: { "XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val() }, success: function (result) { alert(result); } });
解决方法2(不推荐):
在 Startup.cs 的 ConfigureServices 方法中添加:
services.AddRazorPages().AddRazorPagesOptions(o => { o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); });
在 ajax 请求中不添加防伪令牌:
$.ajax({ url: '?handler=Filter2', type: 'POST', contentType: 'application/json; charset=utf-8', success: function (result) { alert(result); } });
注意:第二种方法禁用了防伪验证,存在安全风险,不推荐使用