使用jQuery提交局部视图表单失败的问题排查与解决
问题:jQuery POST请求无法触发后台OnPostFormPartial方法
提交包含表单的局部视图时,编写的jQuery POST请求无法触发Index页面后台的POST方法,希望找出问题所在。
后台代码(Index页面)
[BindProperty] public NotificationFormModel NotificationFormModel { get; set; } public async Task<PartialViewResult> OnGetFormPartial() { NotificationFormModel.Types = await notificationTypeService.GetTypesForDropdownSelectAsync(); return Partial("~/Pages/Partial/_FormPartial.cshtml", NotificationFormModel); } public async void OnPostFormPartial() { string userId = User.GetId()!; await notificationController.CreateNotificationAsync(NotificationFormModel, userId); }
Index页面视图代码
@page @model IndexModel @{ ViewData["Title"] = "Home page"; } <div id="overlay-background"> <div id="notification-form" class="row input-field notification"> </div> </div> <button id="notification-form-button" onclick="showNotificationForm()">Click me for new form</button>
前端脚本代码
function overlayOff() { document.getElementById("overlay-background").style.display = "none"; } function overlayOn() { document.getElementById("overlay-background").style.display = "block"; } function showNotificationForm() { overlayOn(); $(document).on("click", "#notification-form-button", function () { $.ajax({ type: "GET", url: "/Index?handler=FormPartial", success: function (data) { $("#notification-form").html(data); } }); }); } function postNotificationForm() { $(document).on("click", "#notification-submit", function () { $.post("/Index?handler=FormPartial", $("form").serialize(), function () { overlayOff(); }); //$.ajax({ // type: "POST", // url: "/Index?handler=FormPartial", // contentType: "application/json; charset=utf-8", // success: function () { // overlayOff(); // } //}); }); }
局部视图代码(_FormPartial.cshtml)
@using HomeNotifications.Web.Models.Notification @model NotificationFormModel <form method="post"> <div class="form-group"> <label asp-for=Content>Content</label> <input asp-for="Content" class="form-control"> <span asp-validation-for="Content" class="small text-danger"></span> </div> <div class="form-group"> <label asp-for=TypeId>Type</label> <select asp-for="TypeId" class="form-control"> @foreach (var type in Model.Types) { <option value="@type.Id">@type.Name</option> } </select> <span asp-validation-for="TypeId" class="small text-danger"></span> </div> <div class="text-center"> <input id="notification-submit" class="btn btn-primary mt-3" type="submit" value="Create" onclick="postNotificationForm()" /> </div> </form> @section Scripts { <partial name="_ValidationScriptsPartial" /> }
问题解决更新
感谢网友mmm的提示,已找到问题根源并修复:
- 局部视图表单调整:移除form标签的
method="post"属性,将按钮类型从submit改为button,因为项目通过jQuery处理提交,无需表单默认提交行为。 - 后台方法修改:将
OnPostFormPartial的返回类型从async void改为async Task,避免影响控制器和服务方法的正常执行。
内容的提问来源于stack exchange,提问作者Krasimir Dimitrov
相关产品推荐
相关产品推荐

