views:

70

answers:

3

Hi,

I have the following EditorFor template:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<ContactDto>>" %>
<%@ Import Namespace="c2.bases.dto.structure"%>
<%
    for (var i = 0; i < ViewData.Model.Count; i++)
    {%>
         <%=Html.EditorFor(x => x[i])%>
    <%}
%>

The problem is that it is not generating the correct name attribute, it generates the following name attribute for one of the elements:

name="TrainingLookUpContainer.Contacts.[0].Surname"

You can see that there is an extra '.' character after the last Contacts and before the indexer [0].

It should be

name="TrainingLookUpContainer.Contacts[0].Surname"

The object is not getting bound because of this extra '.'.

This editor for is being called from another page like this:

<div style="background: #fff;height:100%">
    <%= Html.EditorFor(x => x.TrainingLookUpContainer.Contacts, "TrainingCategory")%>
</div>

I found this article that seems to suggest I am doing it right link text.

I thought it might be the lamda but I think it might be a bug due to the nesting.

I have a work around where I pass in the Containing object TrainingLookUpContainer and everything is good.

Can anyone suggest a better way of just binding to the List?

Cheers

Paul

A: 

Instead of:

for (var i = 0; i < ViewData.Model.Count; i++)
{%>
     <%=Html.EditorFor(x => x[i])%>
<%}

simply write:

<%= Html.EditorForModel() %>

which will generate correct name attributes and make your code shorter.

Darin Dimitrov
Html.EditorForModel() returns "{}" in this instance.
dagda1
A: 

You shouldn't need this template at all.

MVC 2 already includes a template for collections which does exactly what you want to do, and creates the proper names. You can see the code that's in this template by downloading the MVC 2 Futures package and looking for the EditorTemplates/Collection.ascx file. The names need to be patched up properly, and that code shows you how to do it (if for some reason you can't use the built-in Collection template).

Brad Wilson
A: 

What do you mean he shouldn't use EditorFor x[i]. He should be using any solution that is logical. I, for example, have a similar situation, yet I need to provide a customized add/remove editor for my collection (array, list) property and this issue blocks me completely. I was forced to pass the whole model to the editor just to be able to use this collection property. This Editor thing is a bug, a bug that should have a quickfix soon, a quickfix that can be applied transparently to production servers without a need for administrator to do anything.