2014-04-17 76 views

回答

1

可以迭代的ModelState(這是一個ModelStateDictionary),並期待在鍵,它們對應的屬性

0

伊沙伊的答案是不適合我那麼簡單,所以我想離開以下爲他人結束了的這裏。

以下是我編寫的用於返回所有ModelStateDictionary錯誤的方法,包括髮現錯誤的關鍵字。

public static String GetErrorsJoined(this ModelStateDictionary modelStateDictionary, String separator = ". ") 
    { 
     String errorsJoined = String.Empty; 
     List<String> errors = new List<string>(); 

     try 
     { 

      foreach(KeyValuePair<String, ModelState> keyValuePair in modelStateDictionary) 
      { 
       if (keyValuePair.Value.Errors.Count > 0) 
       { 
        Int32 keyDelimiterIndex = keyValuePair.Key.IndexOf('.'); 
        String realKey = (keyDelimiterIndex > -1 && keyDelimiterIndex + 1 <= keyValuePair.Key.Length - 1) ? keyValuePair.Key.Substring(keyDelimiterIndex + 1) : keyValuePair.Key; 
        IEnumerable<String> keyErrors = keyValuePair.Value.Errors.Select(error => String.Format("{0}{1}{2}", error.ErrorMessage, separator, error.Exception.Message)); 
        errors.Add(String.Format("Field [{0}]: {1}", realKey, String.Join(separator, keyErrors))); 
       } 
      } 

      errorsJoined = String.Join(separator, errors); 
     } 
     catch (Exception ex) 
     { 
      //do something 
     } 

     return errorsJoined; 
    }