2010-02-24 200 views
2

當使用Html.EditorFor並傳遞ViewModel時,可能不會讓每個單獨的表單元素顯示其錯誤消息。Html.EditorFor驗證消息

我正在使用驗證摘要,因此錯誤消息顯示了兩次。一次爲表單元素,然後再次在摘要中。

回答

0

可以通過使用「*」作爲在下面的例子中去除從ValidationMessage錯誤消息刪除個別錯誤。如果您通過錯誤消息傳遞,則會顯示。

<%= Html.ValidationMessage("PropertyName", "*") %> 

如果您通過錯誤消息傳遞,則會顯示它。這也是編輯模板或使用Html.Helper的新版本的λ真正如下圖所示

Html.ValidationMessageFor(m=>m.prop,...) 

希望,幫助,

埃迪

0

您可以創建一個自定義的驗證摘要,並添加所有的錯誤和特殊鍵(在這個例子中,我使用_form例如:

 private const string VALIDATIONSUMMARY_HMTL = "<div class=\"input-validation-error\">{0}</div>"; 

public static string ValidationSummary(this HtmlHelper helper, bool customErrorOnly) 
    { 
     return ValidationSummary(helper, customErrorOnly, "_FORM"); 
    } 

    public static string ValidationSummary(this HtmlHelper helper, bool customErrorOnly, string errorName) 
    { 
     if (helper.ViewData.ModelState.IsValid) 
     { 
      return null; 
     } 

     string list = "<ul>"; 
     bool displayList = false; 
     foreach (KeyValuePair<string, ModelState> pair in helper.ViewData.ModelState) 
     { 
      foreach (ModelError error in pair.Value.Errors) 
      { 
       if (pair.Key.ToUpper() == "_FORM" || !customErrorOnly) 
       { 
        list += "<li>" + error.ErrorMessage + "</li>"; 
        displayList = true; 
       } 
      } 
     } 
     list += "</ul>"; 

     if (!displayList) 
     { 
      return null; 
     } 

     return string.Format(VALIDATIONSUMMARY_HMTL, list); 
    } 

當你想添加一個特定的錯誤:

ViewData.ModelState.AddModelError("_FORM", "My error message");