我曾多次使用 stackoverflow 来解决我的问题(与代码相关!),但这是我第一次需要发布问题,因为我无法找出问题所在。
当我在允许编辑使用 DataAnnotations 进行验证的对象集合的 View 上启用客户端验证时,会引发以下异常:
[KeyNotFoundException: The given key was not present in the dictionary.]
System.Collections.Generic.SortedDictionary`2.get_Item(TKey key) +6129977
System.Web.Mvc.Html.ValidationExtensions.ValidationMessageHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, String expression, String validationMessage, IDictionary`2 htmlAttributes) +840
System.Web.Mvc.Html.ValidationExtensions.ValidationMessageFor(HtmlHelper`1 htmlHelper, Expression`1 expression, String validationMessage, IDictionary`2 htmlAttributes) +138
System.Web.Mvc.Html.ValidationExtensions.ValidationMessageFor(HtmlHelper`1 htmlHelper, Expression`1 expression) +106
ASP.views_test_test_aspx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in d:\SVN\Discover2 - trunk\Discover2.Web\Views\Test\Test.aspx:18
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +109
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
System.Web.UI.Page.Render(HtmlTextWriter writer) +29
System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) +56
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3060
Line 18: <%: Html.ValidationMessageFor(m => Model[i].Name)%>
如果我删除 <% Html.EnableClientValidation(); %>
调用不会引发异常,并且服务器端验证按预期工作。
这是我的测试模型:
public class Dog {
[Required]
public string Name { get; set; }
}
并查看:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IList<Discover2.Web.Controllers.Dog>>" %>
<% Html.EnableClientValidation(); %>
<%using (Html.BeginForm()) { %>
<%for (int i = 0; i < Model.Count(); i++) {%>
<div>
<%: Html.LabelFor(m => Model[i].Name) %>
<%: Html.TextBoxFor(m => Model[i].Name)%>
<%: Html.ValidationMessageFor(m => Model[i].Name)%>
</div>
<%} %>
<button type=submit>Save</button>
任何有关如何使其工作的想法将不胜感激,因为它一直在努力让其工作!!!
谢谢
最佳答案
终于把这个事情搞清楚了。基本上,MVC ValidationMessageHelper 函数无法为验证助手生成的 span 元素生成 id。 TagBuilder 类上的 CreateSanitizedId 方法返回 null,因为 modelName 为“[0].Name”,并且 Id 不能以字母以外的任何内容开头。然后抛出 KeyNotFoundException,因为 TagBuilder 不包含 id。
无论如何,解决这个问题的方法是实现一个简单的 View 模型,而不是直接将模型设置为集合,这样 Dogs 就是模型上的一个属性,因此用于生成 id 的 modelName 变为“Dogs[0] .Name”有效。
关于asp.net-mvc - ASP.Net MVC 2 中列表的客户端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3310774/