views:

183

answers:

2

Hi,

I am trying to find out what would be the best way to bind first element of ISet (Iesi.Collection) as a first element.

So basically I only have to use some kind of collection that has an indexer (and ISet doesn't) then I can write code like this (which works perfectly well):

<%: Html.EditorFor(x => x.Company.PrimaryUsers[0].Email) %>

But as the ISet has no indexer I cannot use it.

So how can I then bind the first element of ISet in MVC2?

Thanks,
Dmitriy.

+1  A: 

Unfortunately those strongly typed helpers work only with indexer properties for collections. They would actually look for opening and closing [ ] brackets in the syntax.

A possible workaround would be to add another property in your view model class which would be of type IList and would be populated from the original property. In the getter you would simply return a new list from the original property and in the setter you would reconstruct the original set as it does not have the notion of order.

Darin Dimitrov
Does not sound any good? I don't want to modify the model just for the sake or rendering it in the view. Definitely better solution should exist.
Dmytrii Nagirniak
A: 

You can pull this off via the following:

<%
  int i = 0;
  foreach (var element in Model.Company.PrimaryUsers) {
    string htmlFieldName = String.Format("Company.PrimaryUsers[{0}]", i);
    %><%: Html.EditorFor(_ => element, null /* templateName */, htmlFieldName) %><%
    i++;
  }
%>

This particular overload of EditorFor() says "I'm going to pass you a model, but use the htmlFieldName string for the model rather than trying to deduce it from the expression." You have to keep track of the i manually in this case.

Levi
This will not bind the posted data back to the model.
Dmytrii Nagirniak