2010-04-05 24 views
1

我目前有一個需要支持兩種不同版本的表單。每個版本可能使用不同的表單字段子集。我必須這樣做來支持兩個不同的客戶端,但我不希望爲這兩個客戶端有完全不同的控制器操作。如何支持模型屬性的條件驗證

所以,我試圖想出一種方法來使用具有驗證屬性的強類型模型,但其中的一些屬性是有條件的。

我能想到的一些方法類似於史蒂夫桑德森的partial validation方法。

我在哪裏清除過濾器中的模型錯誤OnActionExecuting基於表單的哪個版本處於活動狀態。

另一種方法我想會打破模型成使用的東西像塊

class FormModel 
{ 

public Form1 Form1Model {get; set;} 
public Form2 FormModel {get; set;} 
} 

,然後找到一些辦法只有驗證取決於版本的相應屬性。模型上也會有共同的屬性,這兩個屬性都會被驗證。

有沒有人有這方面的好建議?

回答

3

我已經合理成功地使用ModelBinder從ModelState中移除我不需要的錯誤。

下面是一個Address模型活頁夾的示例。在用戶界面中,美國有<SELECT>,但當國家不是'美國'贊成<INPUT ID=StateOrProvince>文本框時隱藏。

modelbinder查看國家並刪除不需要的值。

就驗證屬性而言 - 我認爲除非你有非常簡單的規則,否則你很快就會陷入一團糟。

提示:您可以有儘可能多的模型綁定器,以便對整個模型的各個部分進行謹慎處理。例如 - 我在我的模型中有2個對象,並且每個對象都會自動獲得此行爲。

註冊:

ModelBinders.Binders[typeof(UI.Address)] = new AddressModelBinder(); 

ModelBinder的:

public class AddressModelBinder : DefaultModelBinder 
{ 
    protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     base.OnModelUpdated(controllerContext, bindingContext); 

     // get the address to validate 
     var address = (Address)bindingContext.Model; 

     // remove statecd for non-us 
     if (address.IsUSA) 
     { 
      address.StateOrProvince = string.IsNullOrEmpty(address.StateCd) ? null : CountryCache.GetStateName(address.StateCd); 
      bindingContext.ModelState.Remove(bindingContext.ModelName + ".StateOrProvince"); 
     } 
     else 
     { 
      address.StateCd = null; 
      bindingContext.ModelState.Remove(bindingContext.ModelName + ".StateCd"); 
     } 


     // validate US zipcode 
     if (address.CountryCode == "US") 
     { 
      if (new Regex(@"^\d{5}([\-]\d{4})?$", RegexOptions.Compiled).Match(address.ZipOrPostal ?? "").Success == false) 
      { 
       bindingContext.ModelState.AddModelError(bindingContext.ModelName + ".ZipOrPostal", "The value " + address.ZipOrPostal + " is not a valid zipcode"); 
      } 
     } 

     // all other modelbinding attributes such as [Required] will be processed as normal 
    } 
} 
+0

我喜歡這個主意西蒙。我會放棄它。 – Jeff 2010-04-06 16:50:16

+0

@jeff我起初並不喜歡 - 所以我很高興你已經這麼做了。對於我要完成的簡單任務來說,工作得非常好 – 2010-04-06 19:42:28