Bug with asp.net mvc2, collection and ValidationMessageFor ?

Posted by Rafael Mueller on Stack Overflow See other posts from Stack Overflow or by Rafael Mueller
Published on 2010-04-10T22:03:05Z Indexed on 2010/04/10 22:13 UTC
Read the original article Hit count: 1072

I'm with a really weird bug with asp.net mvc2 (rtm) and ValidationMessageFor.

The example below throws a System.Collections.Generic.KeyNotFoundException on Response.Write(Html.ValidationMessageFor(n => n[index].Name));

Any ideas why thats happening? I'm accessing the same dictionary twice before, but it only throws the error on ValidationMessageFor, any thoughts?

Here's the code.

public class Parent
{
    public IList<Child> Childrens { get; set; }
    [Required]
    public string Name { get; set; }
}

public class Child
{
    [Required]
    public string Name { get; set; }
}

The controller

public class ParentController : Controller
{
    public ActionResult Create()
    {
        var parent = new Parent { Name = "Parent" };
        parent.Childrens = new List<Child> { new Child(), new Child(), new Child() };
        return View(parent);
    }
}

The view (Create.aspx)

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Parent>" %>

<%@ Import Namespace="BugAspNetMVC" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
        <%Html.EnableClientValidation(); %>
<% using (Html.BeginForm())
   {%>
    <%=Html.LabelFor(p => p.Name)%>
    <%=Html.TextBoxFor(p => p.Name)%>
    <%=Html.ValidationMessageFor(p => p.Name)%>
    <%Html.RenderPartial("Childrens", Model.Childrens); %>
    <%} %>
</asp:Content>

And the partial view (Childrens.ascx)

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IList<Child>>" %>
<%@ Import Namespace="BugAspNetMVC"%>

<%

for (int i = 0; i < Model.Count; i++)
{
    var index = i;
    Response.Write(Html.LabelFor(n => n[index].Name));
    Response.Write(Html.TextBoxFor(n => n[index].Name));
    Response.Write(Html.ValidationMessageFor(n => n[index].Name));
}
%>

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about form-validation