2009-10-18 190 views
9

使用VS2008中的MVC項目模板(開箱即用)我注意到以下幾點:Ajax.BeginForm - 顯示驗證錯誤

  1. 這裏是如何指定的Register.aspx形式。

    <% using (Html.BeginForm()) { %> 
    
  2. 選擇註冊按鈕,而不提供任何帳戶信息顯示此。帳戶創建失敗。請更正錯誤並重試。

    •您必須指定一個用戶名。
    •您必須指定一個電子郵件地址。
    •您必須指定一個包含6個或更多字符的密碼。

  3. 我將Register.aspx表單更改爲此。

    <% using (Ajax.BeginForm("Register", new AjaxOptions { HttpMethod = "Post" })) { %> 
    
  4. 選擇註冊按鈕而不提供帳戶信息顯示沒有錯誤。

問題:如何在使用Ajax.BeginForm時顯示錯誤文本?

回答

14

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