2010-09-21 60 views
4

從asp.net背景來看,我非常讚賞在向頁面添加驗證時'validationGroup'的概念。我一直在mvc.net中尋找相應的概念,並沒有太多的運氣。mvc.net驗證支持ValidationGroup的概念

這個概念是否可用於mvc.net?如果沒有,我有什麼替代方案?

+1

一種替代方法是在ASP.NET中無法實現的技術。即,多個

標籤,每個「驗證組」一個。 – 2010-09-21 16:37:43

回答

6

不幸的是,它沒有像這樣的東西。

我在一段時間的博客上寫了一個解決方法。

ASP.NET MVC - Validation Summary with 2 Forms & 1 View

博客文章的JIST:

namespace System.Web.Mvc 
{ 
    public static class HtmlExtensions 
    { 
     public static string ActionValidationSummary(this HtmlHelper html, string action) 
     { 
      string currentAction = html.ViewContext.RouteData.Values["action"].ToString(); 

      if (currentAction.ToLower() == action.ToLower()) 
       return html.ValidationSummary(); 

      return string.Empty; 
     } 
    } 
} 

而且

<h2>Register</h2> 

<%= Html.ActionValidationSummary("Register") %> 

<form method="post" id="register-form" action="<%= Html.AttributeEncode(Url.Action("Register")) %>"> 

    ... blah ... 

</form> 


<h2>User Login</h2> 

<%= Html.ActionValidationSummary("LogIn") %> 

<form method="post" id="login-form" action="<%= Html.AttributeEncode(Url.Action("LogIn")) %>"> 

    ... blah ... 

</form> 

HTHS,
查爾斯

1

查爾斯的方法是我能找到的唯一方法實際爲我的目的工作! (在一個MVC頁面上有兩種形式 - >沒有在partials和partial屬性的ajax加載中執行表單,這對我沒有好處,因爲我想返回不同的結果集以在表單div之外呈現,具體取決於哪個表單提交)

,使客戶端驗證工作我雖然建議稍作修改的HTML擴展,因爲你仍然希望被渲染爲不匹配的驗證摘要驗證摘要:

namespace System.Web.Mvc 
{ 
    public static class HtmlExtensions 
    { 
     public static MvcHtmlString ActionValidationSummary(this HtmlHelper html, string action) 
     { 
      string currentAction = html.ViewContext.RouteData.Values["action"].ToString(); 

      if (currentAction.ToLower() == action.ToLower()) 
       return html.ValidationSummary(); 

      return new MvcHtmlString("<div class=\"validation-summary-valid\" data-valmsg-summary=\"true\"><ul><li style=\"display:none\"></li></ul></div>"); 
     } 
    } 
} 
2

擴展查爾諾的答案,幷包括HtmlAttributes和其他ValidationSummary屬性:

 public static MvcHtmlString ActionValidationSummary(this HtmlHelper html, string action, bool excludePropertyErrors, string message, object htmlAttributes = null) 
    { 
     var currentAction = html.ViewContext.RouteData.Values["action"].ToString(); 

     if (currentAction.ToLower() == action.ToLower()) 
     { 
      return html.ValidationSummary(excludePropertyErrors, message, htmlAttributes); 
     } 

     return new MvcHtmlString(string.Empty); 
    }