如果用户更改了值,只要触发 ,就可以在ASP.NET MVC 3中实现验证的最佳方法。如果当前值无效但用户未更改它,则不应触发。例如
public class SomeViewModel
{
[Required]
[Range(10, 20)]
public int? SomeProperty { get; set; }
public int? AnotherProperty { get; set; }
}
如果用户输入的值超出范围10和20,则默认的ASP.NET MVC验证会在服务器和客户端上触发(不显眼)。但是,如果SomeProperty的当前值无效(例如25)但用户仅更改AnotherProperty的值,则SomeProperty的验证仍会在服务器和客户端上触发。只有当用户没有更改给定属性时,我们如何实现允许现有无效值的验证。因此,在这种情况下,如果SomeProperty的值为25(无效)且用户仅更改AnotherProperty的值,则不应触发验证。如果用户将SomeProperty的值更改为25以外的任何值(当前值),则应对其进行验证,并且不应允许无效值。
答案 0 :(得分:0)
好的,这是可以帮助你的验证属性。
public class RangeIfNotEqualToAttribute : RangeAttribute
{
string otherProperty;
public RangeIfNotEqualToAttribute(string otherProperty, int rangeStart, int rangeEnd) :base(rangeStart,rangeEnd)
{
this.otherProperty = otherProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherPropertyInfo = validationContext.GetType().GetProperty(otherProperty);
var oldValue = (int)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (oldValue == (int)value)
return ValidationResult.Success;
return base.IsValid(value, validationContext);
}
}
它继承自RangeAttribute并返回base.IsValid
如果当前值不等于旧版本(它假设您在同一模型的某些其他属性中携带旧值。所以要使用它,您必须在模型中进行以下更改
public class SomeViewModel
{
public int BackupProperty{get;set;}
[Required]
[RangeIfNotEqualTo("BackupProperty",10, 20)]
public int? SomeProperty { get; set; }
public int? AnotherProperty { get; set; }
}
将模型传递给视图时,您还必须将SomeProperty
的值复制到BackupProperty
。此外,您必须为BackupProperty
呈现隐藏字段,以便随模型回发。如果要实现IClientValidatable
以启用客户端验证,则隐藏字段也很重要。您可以在this post查看类似方案中IClientValidatable
的实施情况