2013-10-02 74 views
0

我想驗證一個模型,其中規則不總是相同的,並且取決於模型中的其他屬性。做這件事的最好方法是什麼?實施例下面:MVC 3我如何驗證整個ViewModel?

假設實施例1

使用MVVM圖案與MVC 3.我的(假設的)視圖模型看起來像這樣:

public string OrderType { get; set; } 
public string Requestor { get; set; } 
public int NumberOfPeanuts { get; set; } 
public int NumberOfJellyBeans { get; set; } 
public int NumberOfAlmonds { get; set; } 

我的觀點基本上看起來像這樣:

@Html.EditorFor(model => model.OrderType) 
@Html.EditorFor(model => model.Requestor) 
@Html.EditorFor(model => model.NumberOfPeanuts) 
@Html.EditorFor(model => model.NumberOfJellyBeans) 
@Html.EditorFor(model => model.NumberOfAlmonds) 

我將如何實現將返回以下規則的「Html.ValidationMessageFor」結果的驗證:

如果訂單類型=「花生」然後NumberOfPeanuts必須大於0,和NumberOfJellyBeans和NumberOfAlmonds必須爲空值或0,否則顯示「這是花生唯一順序」

如果訂單類型=「樣本」然後NumberOfPeanuts + NumberOfJellyBeans + NumberOfAlmonds必須小於30,否則顯示驗證消息「樣本不高的總量不夠」

等...等...

回答

0

我將擴大Sam的答案使用多臺模特屬性來驗證:

public class PeanutOrderAttribute : ValidationAttribute, IClientValidatable 
{ 
    private readonly string _peanutsProperty; 
    private readonly string _orderTypeProperty; 

    public PeanutOrderAttribute(string peanutsPropertyName, string orderTypePropertyName) 
    { 
     _peanutsProperty = peanutsPropertyName; 
     _orderTypeProperty = orderTypePropertyName; 
    } 

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     // get target property and value 
     var peanutInfo = validationContext.ObjectType.GetProperty(this._peanutsProperty); 
     var peanutValue = peanutInfo.GetValue(validationContext.ObjectInstance, null); 

     // get compare property and value 
     var ordertypeInfo = validationContext.ObjectType.GetProperty(this._orderTypeProperty); 
     var ordertypeValue = ordertypeInfo.GetValue(validationContext.ObjectInstance, null); 

     // if validation does not pass 
     if (ordertypeValue == "Peanuts" && peanutValue < 1){ 
      return new ValidationResult("Error Message"); 
     } 

     // else return success 
     return ValidationResult.Success; 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     var rule = new ModelClientValidationRule 
     { 
      ErrorMessage = this.ErrorMessageString, 
      ValidationType = "PeanutOrder" 
     }; 

     rule.ValidationParameters["peanuts"] = this._peanutsProperty; 
     rule.ValidationParameters["ordertype"] = this._orderTypeProperty; 

     yield return rule; 
    } 
} 

然後把驗證標籤上相應的模型屬性:

[PeanutOrder("Peanuts", "OrderType")] 
public int Peanuts{ get; set; } 

public string OrderType { get; set; } 

希望這有助於!

0

你可以用自己的自定義驗證屬性擴展ValidationAttribute

public class CustomAttribute : ValidationAttribute 
{  
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     // validation logic 
    } 
}