2010-06-28 148 views
2

在ASP.NET MVC 2中,我有一個Linq to sql類,它包含一系列字段。現在,當另一個字段具有某個(枚舉)值時,我需要其中一個字段。基於其他領域的驗證?

我已經走了這麼遠,我寫了一個自定義驗證屬性,這可能需要一個枚舉作爲一個屬性,但我不能說,例如:EnumValue = this.OtherField

我應該怎麼辦呢?

+0

我認爲這種驗證必須適用於類,而不是字段。 – Jay 2010-06-28 17:14:06

回答

4

MVC2附帶一個示例「PropertiesMustMatchAttribute」,它顯示瞭如何讓DataAnnotations爲您工作,它應該可以在.NET 3.5和.NET 4.0中工作。該樣本代碼如下所示:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 
public sealed 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); 
     // ignore case for the following 
     object originalValue = properties.Find(OriginalProperty, true).GetValue(value); 
     object confirmValue = properties.Find(ConfirmProperty, true).GetValue(value); 
     return Object.Equals(originalValue, confirmValue); 
    } 
} 

當您使用屬性,而不是把它放在你的模型類的屬性,你把它的類本身:

[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")] 
public class ChangePasswordModel 
{ 
    public string NewPassword { get; set; } 
    public string ConfirmPassword { get; set; } 
} 

當「的IsValid 「調用你的自定義屬性,整個模型實例被傳遞給它,所以你可以通過這種方式獲得相關的屬性值。你可以很容易地遵循這種模式來創建一個更一般的比較屬性。