获取作为字符串传入的属性的值

时间:2012-10-25 14:47:54

标签: c# asp.net-mvc validation

我正在尝试创建一个自定义验证,说明"如果otherValue为true,那么此值必须大于0.我能够获取值,但是我当前拥有otherValue集的方式我只有属性的名称,而不是值。可能是因为它作为一个字符串传入。此属性将在5或6个不同的属性上,每次都会调用不同的otherValue。寻求有关如何获得otherValue的实际值(它是一个bool)的帮助。

这是我目前的代码:

public class MustBeGreaterIfTrueAttribute : ValidationAttribute, IClientValidatable
{
    // get the radio button value
    public string OtherValue { get; set; }

    public override bool IsValid(object value)
    {
        // Here is the actual custom rule
        if (value.ToString() == "0")
        {
            if (OtherValue.ToString() == "true")
            {
                return false;
            }
        }
        // If all is ok, return successful.
        return true;
    }

====================== EDIT ======================== =

这就是我现在的位置,它的确有效!现在我需要参考如何制作它,以便在模型中添加属性时可以输入不同的errorMessage:

public class MustBeGreaterIfTrueAttribute : ValidationAttribute, IClientValidatable
{
    // get the radio button value
    public string OtherProperty { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        var otherPropertyInfo = context.ObjectInstance.GetType();
        var otherValue = otherPropertyInfo.GetProperty(OtherProperty).GetValue(context.ObjectInstance, null);      

        // Here is the actual custom rule
        if (value.ToString() == "0")
        {
            if (otherValue.ToString().Equals("True", StringComparison.InvariantCultureIgnoreCase))
            {
                return new ValidationResult("Ensure all 'Yes' answers have additional data entered.");
            }
        }
        // If all is ok, return successful.
        return ValidationResult.Success;
    }

    // Add the client side unobtrusive 'data-val' attributes
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ValidationType = "requiredifyes";
        rule.ErrorMessage = this.ErrorMessage;
        rule.ValidationParameters.Add("othervalue", this.OtherProperty);
        yield return rule;
    }

}

所以我应该能够做到这一点:

    [MustBeGreaterIfTrue(OtherProperty="EverHadRestrainingOrder", ErrorMessage="Enter more info on your RO.")]
    public int? ROCounter { get; set; }

3 个答案:

答案 0 :(得分:6)

ValidationAttribute有一对IsValid方法,对于您的方案,您必须使用其他人。

  public class MustBeGreaterIfTrueAttribute : ValidationAttribute
  {
    // name of the OtherProperty. You have to specify this when you apply this attribute
    public string OtherPropertyName { get; set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
      var otherProperty = validationContext.ObjectType.GetProperty(OtherPropertyName);

      if (otherProperty == null)
        return new ValidationResult(String.Format("Unknown property: {0}.", OtherPropertyName));

      var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);

      if (value.ToString() == "0")
      {
        if (otherPropertyValue != null && otherPropertyValue.ToString() == "true")
        {
          return null;
        }
      }

      return new ValidationResult("write something here");
    }
  }

使用示例:

public class SomeModel
{
    [MustBeGreaterIf(OtherPropertyName="Prop2")]
    public string Prop1 {get;set;}
    public string Prop2 {get;set;}
}

参考:http://www.concurrentdevelopment.co.uk/blog/index.php/2011/01/custom-validationattribute-for-comparing-properties/

答案 1 :(得分:0)

我在理解你想做什么方面有点麻烦,但是,

如果你想得到OtherValue的布尔表示,你可以做

bool.Parse(this.OtherValue);


另外,对于字符串比较,它有时有助于从图片中取出大小写和空白

if (this.OtherValue.ToString().ToLower().Trim() == "true")

答案 2 :(得分:0)

validationContext具有ObjectInstance,它是SomeModel类的一个实例,因此您可以使用: (validationContext.ObjectInstance as SomeModel).Prop1/Prop2