好的,這是驗證屬性,可能會讓你在那裏。
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
如果電流值不等於舊的一個(它假設你攜帶在同型號的其他一些財產原值。所以使用它,你必須傳遞模型,查看您所需要的SomeProperty
值複製到BackupProperty
以及當你的模型
public class SomeViewModel
{
public int BackupProperty{get;set;}
[Required]
[RangeIfNotEqualTo("BackupProperty",10, 20)]
public int? SomeProperty { get; set; }
public int? AnotherProperty { get; set; }
}
做出以下更改。另外,你必須渲染,因此被調回與模型BackupProperty
隱藏字段。如果您想要im,隱藏字段也很重要請求IClientValidatable
以啓用客戶端驗證。您可以在this post處看到IClientValidatable
在類似場景中的實施
此類行爲不可用於開箱即用。你必須自己編碼。也許通過繼承ValidationAttribute – 2012-01-27 04:44:25
是的,這是有道理的,可能是使用自定義驗證。我想知道如果有人有一些想法或已經看到這樣的事情。需要遺留數據庫具有無效數據的位置,但是需要在修改後的事件上執行驗證。 – 2012-01-27 05:28:45