要成功应用 ajax 表单提交,您必须修改注册操作和视图。默认情况下,如果发生错误,此操作仅返回关联的 register.aspx 视图。第一步是将验证摘要放在部分用户控件中:
验证摘要.ascx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.ValidationSummary("Account creation was unsuccessful. Please correct the errors and try again.") %>
然后将此部分包含在 Register.aspx 视图中:
<div id="validationSummary">
<% Html.RenderPartial("ValidationSummary"); %>
</div>
<% using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "validationSummary" })) { %>
FORM CODE HERE
<% } %>
最后修改注册操作:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string userName, string email, string password, string confirmPassword)
{
// ... skipped content for clarity
// If we got this far, something failed, redisplay form
if (Request.IsAjaxRequest())
{
// If an ajax request was made return only the validation errors
// instead of the whole page
return PartialView("ValidationSummary");
}
else
{
return View();
}
}
如果默认情况下注册成功,Register 操作只会重定向到 Home/Index。您还必须修改此位,因为当您执行 ajax 请求时,重定向将不起作用。同样的方式,您可以测试您是否正在异步调用操作并返回一些表明注册成功的文本。此文本将显示在与div
验证错误相同的内部。
更新:
最后一个问题 - 我如何使用 Html.ValidationMessage("....") 方法让每个控件错误消息呈现在控件旁边,而不是错误消息的项目符号列表?
为了实现这一点,您需要将表单的内容放在局部视图中:
<% using (Ajax.BeginForm(
"register",
null,
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "myForm"
},
new {
id = "myForm"
})) { %>
<% Html.RenderPartial("RegisterForm"); %>
<% } %>
并在您的注册操作中呈现正确的部分:
if (Request.IsAjaxRequest())
{
return PartialView("RegisterForm");
}
else
{
return View();
}