2011-12-29 45 views
3

我們已經在MVC3項目之一創建了以下視圖模型驗證消息:順序自定義屬性在MVC3視圖模型

[PropertiesMustMatch("Email", "ConfirmEmail", ErrorMessage = "The email address you provided does not match the email address in the confirm email box.")] 
[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password you provided does not match the confirmation password in the confirm password box.")] 
public class ActivationStep2ViewModel 
{ 
    ..... 

的PropertiesMustMatch是一個自定義屬性,我們已經創建,如下面的代碼:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 
public class PropertiesMustMatchAttribute : ValidationAttribute 
{ 
    private const string _defaultErrorMessage = "'{0}' and '{1}' do not match."; 
    private readonly object _typeId = new object(); 

    public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty) 
     : base(_defaultErrorMessage) 
    { 
     OriginalProperty = originalProperty; 
     ConfirmProperty = confirmProperty; 
    } 

    public string ConfirmProperty { get; private set; } 
    public string OriginalProperty { get; private set; } 

    public override object TypeId 
    { 
     get 
     { 
      return _typeId; 
     } 
    } 

    public override string FormatErrorMessage(string name) 
    { 
     return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, 
      OriginalProperty, ConfirmProperty); 
    } 

    public override bool IsValid(object value) 
    {    
     PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); 
     object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value); 
     object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value); 
     return Object.Equals(originalValue, confirmValue); 
    } 
} 

然而,在視圖上,當存在兩個1)電子郵件和確認電子郵件和2)的口令及確認口令之間不匹配時,顯示在頂部密碼的驗證消息。請參見下面的圖片:

enter image description here

我們想在頂部顯示的電子郵件文本框的驗證消息,因爲這些文本框前的密碼文本框出現。

注意:本地構建(通過VS2010)的消息順序按預期工作。消息的順序僅在我們的DEV和TEST環境中搞砸了。縱觀通過反射部署的DLL,這是顯示的內容:(屬性的順序是相反的)

enter image description here

我們能做些什麼來解決這個問題的發佈版本? 任何幫助/建議將不勝感激。

謝謝。

回答

3

我們仍然不知道爲什麼編譯器混淆了驗證屬性設置的順序,有點廢話!我們不得不用不同的方法來解決這個問題。

我們擺脫了自定義驗證屬性,並在視圖模型上實現了IValidatableObject。在驗證方法中,按照我們希望顯示的消息的順序添加驗證邏輯(代碼如下):

public class ActivationStep2ViewModel : IValidatableObject 
{ 
. 
. 
. 
. 
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
     if(Email != ConfirmEmail) 
     { 
      yield return new ValidationResult("The email address you provided does not match the email address in the confirm email box."); 
     } 

     if(NewPassword != ConfirmPassword) 
     { 
      yield return new ValidationResult("The new password you provided does not match the confirmation password in the confirm password box."); 
     } 
    } 
相關問題