asp.net MVC - ValidationSummary 不顯示
我有一個奇怪的問題,即沒有顯示 ValidationSummary。但是,正在顯示 ValidationMessage。我已經檢查了輸出頁面的原始碼,但並不是它們的顏色會掩蓋它們。我正在使用RC。有任何想法嗎?
編輯:在 ValidationSummary 設置的斷點顯示:
ViewData.ModelState.Values[1].ErrorMessage = "" ViewData.ModelState.Values[1].Exception.InnerException.Message = "4a is not a valid value for Int32"ValidationSummary 是否使用 ErrorMessage,而 ValidationMessage 是否使用 InnerException.Message?
我的視圖程式碼是:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<App.Models.PurchaseOrdersView>" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> <title>Edit</title> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Edit</h2> <%= Html.ValidationSummary() %> <% Html.BeginForm("Edit", "PurchaseOrder", FormMethod.Post); %> <table> <tr> <td> Purchase Order Id: </td> <td> <%= Html.TextBox("PurchaseOrderId", Model.PurchaseOrderId)%> <%= Html.ValidationMessage("PurchaseOrderId")%> </td> </tr> <tr> <td> Date: </td> <td> <%= Html.TextBox("Date", Model.Date.ToString("dd-MMM-yyyy"))%> <%= Html.ValidationMessage("Date")%> </td> </tr> </table> <input type="submit" value="Save" /> <% Html.EndForm(); %> </asp:Content>
您沒有說沒有顯示的錯誤是什麼,但是有一些錯誤將顯示在 ValidationMessage 中,但不會顯示在 ValidationSummary 中。我認為這是候選版本中的一個錯誤,但我對其他解釋持開放態度。特別是,請考慮 ValidationSummary 原始碼中的這一行:
string errorText = GetUserErrorMessageOrDefault(modelError, null /* modelState */);請注意,沒有為 modelState 傳遞任何內容。現在將其與 ValidationMessage 進行對比:
... GetUserErrorMessageOrDefault(modelError, modelState) ...最後,我們看一下GetUserErrorMessageOrDefault:
private static string GetUserErrorMessageOrDefault(ModelError error, ModelState modelState) { if (!String.IsNullOrEmpty(error.ErrorMessage)) { return error.ErrorMessage; } if (modelState == null) { return null; } string attemptedValue = (modelState.Value != null) ? modelState.Value.AttemptedValue : null; return String.Format(CultureInfo.CurrentCulture, MvcResources.Common_ValueNotValidForProperty, attemptedValue); }這告訴我們的是,如果您在向模型狀態添加錯誤時指定自定義錯誤消息,它將被顯示。但是,如果添加了一個異常(AddModelError 有一個重載接受一個異常,另一個重載接受一個字元串;實現 IDataErrorInfo 的工作方式類似於字元串大小寫),而不是字元串錯誤消息,只有在 modelState 為非空,然後我們會給你一個通用消息而不是異常的錯誤消息。
更新
ValidationSummary 是否使用 ErrorMessage,而 ValidationMessage 是否使用 InnerException.Message?
是的,或多或少是這樣的效果。就像我說的,我認為這是一個錯誤。
更新2
Microsoft 更新了 GetUserErrorMessageOrDefault 函式,如此處所示。
private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState) { if (!String.IsNullOrEmpty(error.ErrorMessage)) { return error.ErrorMessage; } if (modelState == null) { return null; } string attemptedValue = (modelState.Value != null) ? modelState.Value.AttemptedValue : null; return String.Format(CultureInfo.CurrentCulture, GetInvalidPropertyValueResource(httpContext), attemptedValue); }
嘗試
<%= Html.ValidationSummary(false) %>