要成功应用ajax表单提交,您将不得不修改注册操作和视图。默认情况下,如果发生错误,此操作只返回关联的register.aspx视图。第一步将是把验证摘要部分用户控件内:
ValidationSummary.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();
}
}
如果注册默认成功注册操作只是重定向到Home/Index。您也必须修改此位,因为在执行ajax请求时,重定向不起作用。如果您异步调用该操作并返回一些表明注册成功的文本,则可以测试该方法。此文本将作为验证错误显示在相同的div
内。
UPDATE:
最后一个问题 - 不是错误消息的 符号列表,怎么办 我得到使用 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();
}