2012-01-27 25 views
0

什麼是在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

此類行爲不可用於開箱即用。你必須自己編碼。也許通過繼承ValidationAttribute – 2012-01-27 04:44:25

+0

是的,這是有道理的,可能是使用自定義驗證。我想知道如果有人有一些想法或已經看到這樣的事情。需要遺留數據庫具有無效數據的位置,但是需要在修改後的事件上執行驗證。 – 2012-01-27 05:28:45

回答

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如果電流值不等於舊的一個(它假設你攜帶在同型號的其他一些財產原值。所以使用它,你必須傳遞模型,查看您所需要的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在類似場景中的實施