0

我在我的asp.net MVC2項目所做的自定義屬性:閱讀asp.net mvc2自定義屬性中另一個屬性的值?

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 
public class IsUsernameValidAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) 
    { 
     if (value == null) 
     { 
      return true; 
     } 

     var username = value.ToString(); 

     return UserBusiness.IsUsernameValid(username) 
// && value of OtherProperty == true; 
    } 
} 

的模型:

public class MyClass 
{ 
    [IsUsernameValid] 
    public string UserName { get; set; } 

    public bool OtherProperty { get; set; } 
} 

我可以得到用戶名的價值,但我可以得到OtherProperty的值自定義屬性裏面並用它作爲回報條款和方式。提前致謝。

+0

你試過重寫'IsValid(Object,ValidationContext)'重載嗎? – svick

+0

那麼,我想布爾作爲返回值,這個重載有ValidationContext返回值...任何其他幫助? – Cemsha

+0

你肯定你不能使用下面的代碼進行驗證: 公衆覆蓋的ValidationResult的IsValid(對象的值,ValidationContext上下文) {VAR 用戶= context.ObjectInstance爲MyClass的; bool結果= ... //您的驗證邏輯在這裏 返回結果? ValidationResult.Success:new ValidationResult(FormatErrorMessage(context.DisplayName)); } – STO

回答

1

要做到這一點的唯一方法是使用類級別屬性。這通常用於在註冊期間驗證PasswordPasswordConfirmation字段。

以部分代碼from there爲起點。

[AttributeUsage(AttributeTargets.Class)] 
public class MatchAttribute : ValidationAttribute 
{ 
    public override Boolean IsValid(Object value) 
    { 
     Type objectType = value.GetType(); 

     PropertyInfo[] properties = objectType.GetProperties(); 

     ... 
    } 
}