2011-05-25 91 views
0

我在模型類的某些屬性上有一些標準驗證器屬性。 HTML表單發佈到我的控制器,我可以檢查ModelState以查看它是否有效,並查看哪些屬性無效。這很好。 (我沒有做任何客戶端驗證。)如何在ASP.NET MVC 3的模型中找到驗證器類型失敗的內容?

但是,在某些時候,如果唯一屬性未通過驗證的是其上的RequiredAttribute,我想將該模型視爲有效。

我可以使用Reflection來檢查每個驗證失敗的屬性,並查看每個屬性在其自定義屬性中是否有RequiredAttribute,但這看起來有點沉重。是否有一些我不知道的API會告訴我失敗的驗證器的類型?

回答

1

好吧,一個瘋狂的需求需要一個瘋狂的解決方案!在我的控制,我用 if(this.ModelState.IsValid)...,但現在我可以用 if(ValidatorChecker<ModelType>.IsModelStateValid(this.ModelState))...
有以下幾點:

internal static class ValidatorChecker<TModel> 
{ 
    public static bool IsModelStateValid(ModelStateDictionary modelState) 
    { 
     if (modelState.IsValid) 
     { 
     return true; 
     } 

     int totalErrors = 0, requiredAttributeErrors = 0; 
     Type modelType = typeof(TModel); 
     foreach (var key in modelState.Keys) 
     { 
     if (modelState[key].Errors.Count > 0) 
     { 
      totalErrors += modelState[key].Errors.Count; 

      Type currentType = modelType; 
      string[] typeParts = key.Split(
       new char[] { '.' }, 
       StringSplitOptions.RemoveEmptyEntries); 
      int typeIndex = 0; 

      if (typeParts.Length == 0) 
      { 
       continue; 
      } 
      else if (typeParts.Length > 1) 
      { 
       for (typeIndex = 0; typeIndex < typeParts.Length - 1; typeIndex++) 
       { 
        currentType = 
        currentType.GetProperty(typeParts[typeIndex]).PropertyType; 
       } 
      } 

      PropertyInfo validatedProperty = 
       currentType.GetProperty(typeParts[typeIndex]); 

      var requiredValidators = 
       validatedProperty.GetCustomAttributes(typeof(RequiredAttribute), true); 
      requiredAttributeErrors += requiredValidators.Length; 
     } 
     } 

     return requiredAttributeErrors == totalErrors; 
    } 
} 
0

驗證發生是由於模型綁定從HTTP請求中提取的形式集合的一部分和應用驗證屬性。我會建議構建一個驗證屬性來實現您需要的驗證。目前正在執行的驗證幾乎沒有意義,因爲它沒有告訴你哪個字段是無效的。

在許多請求中也有很多次執行此反射的速度含義,它可能是ssssslllllllooooowwwwwww !!!