您需要创建自定义验证属性 - 网上有很多帮助。以下是对类似依赖属性的改编。
public class GreaterThanOtherAttribute : ValidationAttribute, IClientValidatable
{
public string DependentProperty { get; set; }
public GreaterThanOtherAttribute (string dependentProperty)
{
this.DependentProperty = dependentProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get a reference to the property this validation depends upon
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(this.DependentProperty);
if (field != null)
{
// get the value of the dependent property
var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);
// compare the value against the target value
if ((dependentvalue == null && this.TargetValue == null) ||
(dependentvalue != null && dependentvalue < this.TargetValue)))
{
// match => means we should try validating this field
return new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
,然后装点你的模型:
public class id
{
[Required]
public decimal l_ID
{
get;
set;
}
[Required]
[GreaterThanOtherAttribute("l_ID")]
public decimal v_ID
{
get;
set;
}
}
你现在需要做的是找到一个示例自定义属性,并适应它使用上面。
健康警告 - 这未经任何测试,可能包含错误。
祝你好运!
太棒了!这工作。只是一个快速跟进问题。如果我想将输入v_ID的用户与从URL传入的参数进行比较,那么验证规则将如何更改,如何从浏览器中获取该参数。 – deep
ViewModel的URL参数部分,还是可以?我就是这么做的。 ViewModel应该包含“页面”运行操作所需的所有内容。一旦所有内容都在ViewModel中,Validate方法只需查看这些字段即可完成其逻辑。用特定的scenerio回到这里,或者打开一个更新,更具体的问题(并让我知道)。 – Graham
是的,我添加了两个字段,如old_v_id和old_l_id到viewmodel,我现在应该可以使用它。非常感谢 – deep