4

在 ASP.NET MVC 2 中,我有一个包含一系列字段的 Linq to sql 类。现在,当另一个字段具有某个(枚举)值时,我需要其中一个字段。

到目前为止,我编写了一个自定义验证属性,它可以将枚举作为属性,但我不能说,例如:EnumValue = this.OtherField

我该怎么做?

4

1 回答 1

5

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”时,整个模型实例都会传递给它,因此您可以通过这种方式获取相关属性值。您可以轻松地按照此模式创建更通用的比较属性。

于 2010-06-29T10:38:58.477 回答