ASP.NET Core 7 MVC如何在Register动作完成前更新视图?
问题:ASP.NET Core 7 MVC注册动作耗时,如何在动作完成前更新视图?
在ASP.NET Core 7 MVC项目的Register视图中,由于对应POST动作包含耗时操作(如创建用户、发送邮件/短信),需要在模型验证通过后、动作完成前立即禁用页面部分元素。
尝试通过在控制器中调用View(model).ExecuteResultAsync(ControllerContext)提前返回视图,代码如下:
[HttpPost] public async Task<IActionResult> Register(RegisterViewModel model) { IActionResult actionResult = null; if (model.Submitted = ModelState.IsValid) { await View(model)?.ExecuteResultAsync(ControllerContext); //await PartialView("UserAccountSubmittedPartial")?.ExecuteResultAsync(ControllerContext); if (string.IsNullOrWhiteSpace(model.UserName)) { model.UserName = UserManager.GenerateNewUserName(); } BankApiUser newUser = new BankApiUser(model); IdentityResult identityResult = IdentityResult.Success; try { identityResult = await UserManager.CreateAsync(newUser, model.Password); } catch(Exception e) { IdentityResult.Failed(new IdentityError() { Description = e.Message }); Debug.WriteLine(e); throw e; } if (identityResult?.Succeeded == true) { switch(model.LoginType) { case LoginType.LoginByUserName: actionResult = RedirectToAction("Login", newUser); break; case LoginType.LoginByEmail: await EmailHelper.SendConfirmationLinkMail(HttpContext, model); actionResult = View(model); break; case LoginType.LoginByPhoneNumber: await SmsHelper.SendVerificationCode(model); actionResult = View(model); break; } } else { actionResult = View(model); } } else { actionResult = View(model); } return actionResult; }
但该方法存在两个问题:
- Register视图中的脚本未执行
- 视图内容重复显示
另外尝试通过执行包含更新脚本的局部视图PartialViewResult,结果动作执行后出现HTTP 500错误。
需要找到正确的方式,在Register动作完成前通过脚本更新视图。
解决方案
移除控制器中的表单提交逻辑,将其迁移至JavaScript的onsubmit事件中:
- 在表单的
onsubmit事件中,先完成客户端模型验证 - 验证通过后立即禁用目标元素(如提交按钮、输入框)
- 通过AJAX请求向服务器发送注册数据,获取服务器端的模型验证状态、处理结果等
- 根据AJAX返回的结果,再执行后续页面更新(如显示提示、跳转页面等)
这样就能在耗时操作开始前立即更新页面状态,避免用户重复提交,同时解决了服务器端提前返回视图导致的脚本不执行、内容重复问题。
内容的提问来源于stack exchange,提问作者Stanislav
相关产品推荐
相关产品推荐

