Search code examples
asp.net-mvcdisplay-templates

MVC 3 multiple DisplayFor-Templates


I'm trying to make a custom template for a basket item list. I need a few different templates, as I have different ways of displaying the item, depending on if it's on the webpage or in a mail. Now my problem is, that when I use the default name it works flawlessly.

@Html.DisplayFor(b => b.Items)

But when I try to add a template name, I get an expection that my templates needs to be of a list type IEnumerable and not BasketItem.

@Html.DisplayFor(i => basket.Items, "CustomerItemBaseList")

Any ideas where my mistake is, or why it's not possible are appreciated. Thanks.


Solution

  • Unfortunately that's a limitation of templated helpers. If you specify a template name for a collection property the template no longer applies automatically for each item of the collection. Possible workaround:

    @for (int i = 0; i < Model.Items.Length; i++)
    {
        @Html.DisplayFor(x => x.Items[i], "CustomerItemBaseList")
    }