asp.net-mvc – 依赖于另一个字段的属性

在我的ASP.NET MVC应用程序的模型中,我想要验证一个文本框,只有当选中了一个特定的复选框时才需要。

就像是

public bool retired {get,set};

[requiredIf("retired",true)]
public string retirementAge {get,set};

我怎样才能做到这一点?

谢谢。

解决方法

看看这个: http://blogs.msdn.com/b/simonince/archive/2010/06/04/conditional-validation-in-mvc.aspx

我已经修改代码,以满足我的需要。也许你也受益于这些变化。

public class requiredIfAttribute : ValidationAttribute
{
    private requiredAttribute innerAttribute = new requiredAttribute();
    public string DependentUpon { get; set; }
    public object Value { get; set; }

    public requiredIfAttribute(string dependentUpon,object value)
    {
        this.DependentUpon = dependentUpon;
        this.Value = value;
    }

    public requiredIfAttribute(string dependentUpon)
    {
        this.DependentUpon = dependentUpon;
        this.Value = null;
    }

    public override bool IsValid(object value)
    {
        return innerAttribute.IsValid(value);
    }
}

public class requiredIfValidator : DataAnnotationsModelValidator<requiredIfAttribute>
{
    public requiredIfValidator(ModelMetadata Metadata,ControllerContext context,requiredIfAttribute attribute)
        : base(Metadata,context,attribute)
    { }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        // no client validation - I might well blog about this soon!
        return base.GetClientValidationRules();
    }

    public override IEnumerable<ModelValidationResult> Validate(object container)
    {
        // get a reference to the property this validation depends upon
        var field = Metadata.ContainerType.GetProperty(Attribute.DependentUpon);

        if (field != null)
        {
            // get the value of the dependent property
            var value = field.GetValue(container,null);

            // compare the value against the target value
            if ((value != null && Attribute.Value == null) || (value != null && value.Equals(Attribute.Value)))
            {
                // match => means we should try validating this field
                if (!Attribute.IsValid(Metadata.Model))
                    // validation Failed - return an error
                    yield return new ModelValidationResult { Message = ErrorMessage };
            }
        }
    }
}

然后使用它:

public DateTime? DeptDateTime { get; set; }
[requiredIf("DeptDateTime")]
public string DeptAirline { get; set; }

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...