2010-05-03 111 views
5

問題是:當我在頁面上放置2個相同類型的控件時,我需要爲綁定指定不同的前綴。在這種情況下,驗證規則在表單不正確後立即生成。因此,如何讓客戶端驗證工作的情況?:Asp.Net MVC2帶前綴控件的客戶端驗證問題

頁面包含:

<% 
    Html.RenderPartial(ViewLocations.Shared.PhoneEditPartial, new PhoneViewModel { Phone = person.PhonePhone, Prefix = "PhonePhone" }); 
    Html.RenderPartial(ViewLocations.Shared.PhoneEditPartial, new PhoneViewModel { Phone = person.FaxPhone, Prefix = "FaxPhone" }); 
%> 

控制ViewUserControl <PhoneViewModel>:

<%= Html.TextBox(Model.GetPrefixed("CountryCode"), Model.Phone.CountryCode) %> 
<%= Html.ValidationMessage("Phone.CountryCode", new { id = Model.GetPrefixed("CountryCode"), name = Model.GetPrefixed("CountryCode") })%> 

其中Model.GetPrefixed("CountryCode")剛剛返回 「FaxPhone.CountryCode」或「PhonePhone.CountryCode」取決於前綴


這裏是表單之後生成的驗證規則。它們被複製爲字段名稱「Phone.CountryCode」。雖然期望的結果是2條規則(必需的,數目)對於每個FIELDNAMES「FaxPhone.CountryCode」的,「PhonePhone.CountryCode」 alt text http://www.freeimagehosting.net/uploads/37fbe720bf.png

問題是有些重複的Asp.Net MVC2 Clientside Validation and duplicate ID's problem 但提醒手動生成的ID沒有按沒有幫助。

回答

10

同時設置爲文本框和驗證相同前綴的正確方法:

<% using (Html.BeginHtmlFieldPrefixScope(Model.Prefix)) { %> 
    <%= Html.TextBoxFor(m => m.Address.PostCode) %> 
    <%= Html.ValidationMessageFor(m => m.Address.PostCode) %> 
<% } %> 

其中

public static class HtmlPrefixScopeExtensions 
{ 
    public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix) 
    { 
     return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix); 
    } 

    private class HtmlFieldPrefixScope : IDisposable 
    { 
     private readonly TemplateInfo templateInfo; 
     private readonly string previousHtmlFieldPrefix; 

     public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix) 
     { 
      this.templateInfo = templateInfo; 

      previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix; 
      templateInfo.HtmlFieldPrefix = htmlFieldPrefix; 
     } 

     public void Dispose() 
     { 
      templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix; 
     } 
    } 
} 

(偶然發現史蒂夫·桑德森的博客http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/中的代碼解決方案)

也看起來像Html.EditorFor方法應該工作以及在這裏建議:ASP.NET MVC 2 - ViewModel Prefix

+0

不錯。這個答案非常有幫助。希望我能多勞多得。 – 2010-08-04 18:40:46

+0

非常非常有幫助。謝謝。 – Luke 2011-06-09 19:43:08

+0

我知道這是一箇舊的答案,但我想知道如果你的方法是把這個放在你的視圖:ViewData.TemplateInfo.HtmlFieldPrefix =「myViewModel.MyCustomObjdect」; – 2011-11-28 19:52:37