要成功應用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();
}