【问题标题】:MVC3 Model Validation (Compare propery in another class)MVC 模型验证(比较另一个类中的属性)
【发布时间】:2012-07-25 17:59:36
【问题描述】:
public class User
{
string username;
string password;
}

public class registration
{
User user;
**[compare(user.password)]**
string newPass;
}

它产生错误(找不到属性) 有没有办法为另一个类中的属性创建验证?

谢谢

【问题讨论】:

  • 我刚刚找到了如何创建自定义验证。
  • 请发表您的答案,以帮助其他人

标签: asp.net-mvc-3 validation model


【解决方案1】:
public class CompareOther:ValidationAttribute, IClientValidatable
{
private readonly string testedPropertyName;
private readonly string className;

public CompareOther(string testedPropertyName)
{
    string[] word = testedPropertyName.Split('.');
    this.testedPropertyName = word[1];
    this.className = word[0];
}

protected override ValidationResult IsValid(object value, ValidationContext     validationContext)
{
    var propertyTestedInfo = validationContext.ObjectType.GetProperty(this.className);

    if (propertyTestedInfo == null)
    {
        //return new ValidationResult("unknown property");
        return new ValidationResult(string.Format("unknown property {0}.{1}",this.className ,this.testedPropertyName));
    }

    var propertyObject = propertyTestedInfo.GetValue(validationContext.ObjectInstance,null);
    var propertyTestedValue = getValue(testedPropertyName,propertyObject);


    if (value == null)
    {
        return ValidationResult.Success;
    }

    if (propertyTestedValue == null)
    {
        return ValidationResult.Success;
    }

    if (propertyTestedValue.ToString() == value.ToString())
    {
        return ValidationResult.Success;
    }


   return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); 
}

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    var rule = new ModelClientValidationRule
    {
        ErrorMessage = this.ErrorMessageString,
        ValidationType = "lessthan"
    };
    rule.ValidationParameters["propertytested"] = this.testedPropertyName;

    yield return rule;
}

private Object getValue(string name,Object obj)
{
    if (obj == null)
        return null;
    Type type = obj.GetType();
    PropertyInfo info = type.GetProperty(name);
    if (info == null)
    { return null; }
    obj = info.GetValue(obj, null);
    return obj;
}

}

【讨论】:

  • 可能有更好的方法来做到这一点,但这就是我所做的
猜你喜欢
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多