Razor Page表单提交无法命中Post断点,OnGet断点也不触发求助
问题修复方案
核心错误原因
- Waiver.cshtml的
@model绑定错误:Razor Page要求视图必须绑定对应继承自PageModel的后台处理类,你当前绑定的是实体类GCRR.Models.WaiverLookup,和后台的GCRR.Pages.WaiverModel完全脱钩,所以OnGet、OnPost的断点都不会触发。
配套修改点
- 修正
@model绑定后,需要在WaiverModel中添加带[BindProperty]特性的WaiverLookup公开属性,用来接收表单提交的数据。 - 视图内所有
asp-for属性的绑定路径要同步修改为PageModel下对应的属性。 - 建议使用异步
OnPostAsync方法替代同步OnPost方法,符合ASP.NET Core开发最佳实践。
修正后完整代码
Waiver.cshtml
@page @model GCRR.Pages.WaiverModel @{ ViewData["Title"] = "Waiver lookup page"; } <div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <h1 class="page-header"> Sign a new or lookup an existing liability waiver </h1> </div> </div> <form method="post"> <div class="row"> <br /> <h3> If you have signed a waiver that included the participates that are with you today, adults and/or kids, then enter your phone number or email address to lookup your waiver. You will need this when purchasing tickets. If you have never signed a waiver before please click the new waiver button. </h3> </div> <br /> <div class="row"> <div class="col-md-6"> <div class="row form-group"> <label asp-for="WaiverLookup.Phone" class="col-xs-12">Phone</label> <div class="col-xs-9"><input asp-for="WaiverLookup.Phone" class="form-control" /></div> <span asp-validation-for="WaiverLookup.Phone" class="text-danger"></span> </div> <br />or<br /><br /> <div class="row form-group"> <label asp-for="WaiverLookup.Email">Email</label> <div><input asp-for="WaiverLookup.Email" class="form-control" /></div> <span asp-validation-for="WaiverLookup.Email" class="text-danger"></span> </div> <div class="row form-group"> <input type="submit" class="btn btn-primary pull-right"> </div> </div> </div> </form> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
Waiver.cshtml.cs
using GCRR.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using GCRR.Models; namespace GCRR.Pages { public class WaiverModel : PageModel { private readonly IWaiverFileService _waiverFileService; [BindProperty] public WaiverLookup WaiverLookup { get; set; } public WaiverModel(IWaiverFileService waiverFileService) { _waiverFileService = waiverFileService; } public void OnGet() { } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } // 实际使用时可替换为WaiverLookup.Phone或WaiverLookup.Email获取提交的查询条件 var waivers = await _waiverFileService.SearchWaiversAsync("8137812796"); return RedirectToPage("./Index"); } } }
内容的提问来源于stack exchange,提问作者Chris Ward
相关产品推荐
相关产品推荐

