【问题标题】:Read value of another property in asp.net mvc2 custom attribute?读取asp.net mvc2自定义属性中另一个属性的值?
【发布时间】:2011-11-10 06:28:35
【问题描述】:

我在我的 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; }
}

我可以获取 UserName 的值,但我可以在自定义属性中获取 OtherProperty 的值并在 return 子句中使用它以及如何使用它。提前致谢。

【问题讨论】:

  • 您是否尝试过覆盖IsValid(Object, ValidationContext) 重载?
  • 嗯,我想要 bool 作为返回值,这个重载有 ValidationContext 返回值...还有其他帮助吗??
  • 您确定不能使用以下代码进行验证: public override ValidationResult IsValid(object value, ValidationContext context) { var user = context.ObjectInstance as MyClass; bool result = ... // 你的验证逻辑在这里返回结果? ValidationResult.Success : 新的 ValidationResult(FormatErrorMessage(context.DisplayName)); }
  • 当我使用“public override ValidationResult IsValid(object value, ValidationContext context)”时,context为null....

标签: c# asp.net-mvc-2 properties custom-attributes asp.net-mvc-validation


【解决方案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();

        ...
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    相关资源
    最近更新 更多