mardi 5 mai 2015

Using the collection's DisplayName from within DisplayTemplate for a single element

To begin with, the code we have no problems with. It's a model:

    [DisplayName("A very hot hotshot")]
    public Person Hotshot { get; set; }

    [DisplayName("Just a developer")]
    public Person Developer { get; set; }

    [DisplayName("Some random guy")]
    public Person RandomGuy { get; set; }

And then we have a view which looks like this:

@Html.DisplayFor(m=>m.Hotshot)
@Html.DisplayFor(m=>m.Developer)
@Html.DisplayFor(m=>m.RandomGuy)

DisplayTemplate for Person has a line which uses model's DisplayName:

@Html.DisplayNameForModel()

It's all nice, but the problem appears when you add a list property to the model and try to display it with DisplayFor. Here's the model part:

[DisplayName("Funny guys")]
public IEnumerable<Person> FunnyGuys { get; set; }

And, as DisplayFor is capable of displaying IEnumerable<T> iterating the T template, I'm calling it just like for other properties:

@Html.DisplayFor(m=>m.FunnyGuys)

It works great, except for fetching that DisplayName from the containing collection. It's set to null, since the attribute is on IEnumerable property, and the template gets a single element from it.

I had to use the workaround:

@Html.DisplayFor(m=>m.FunnyGuys, new {CollectionDisplayName = "Funny guys"})

And then using that property if DisplayName is null in Person template.

Is there a cleaner way?

Aucun commentaire:

Enregistrer un commentaire