Collections and ASP.NET MVC Templated Helpers – Part 2

This is part of a mini-series:

  • Part 1 – Define the problem & give a workaround
  • Part 2 – Show an alternative workaround
  • Part 3 – Show a reusable, simple solution
  • Part 4 – Replacing Object.ascx

Last time I outlined a problem that I was having with rendering a collection via the templated helpers. The workaround that I showed in that post involved using a custom collection type, however there are times when this isn’t necessarily an option. In the scenario where I encountered the problem I was using Entity Framework (v1) classes as part of my model and so was forced to use EntityCollection<T>. (Note: for a good write-up of the options for your models see my colleague Simon’s post on the topic)

Fortunately, there are at least a couple of alternative approaches to tackling the problem. Another way is to take greater control over the template output. So, with the original Foo defintion from last time:

public class Foo
    public int Id { get; set; }
    public List<Bar> Bars { get; set; }

And the view that uses the templated helper:

<%= Html.DisplayForModel() %>

I can then create a Foo.ascx in the DisplayTemplates. At this point the DisplayForModel above will simply use the Foo.ascx provided. I can still use the templated helpers in the definition of Foo.ascx:

<%= Html.DisplayFor(m=>m.Id) %>
<%= Html.DisplayFor(m=>m.Bars, "BarList") %>

This use of the templated helpers means that I still get the benefit of any metadata that I’ve provided to customise the display of Foo’s properties (e.g. if there was an Email property with the DataType(DataType.Email) annotation then by default it would display as a mailto link)

Even so, I still wasn’t quite happy with this as a solution. Next time I’ll show a solution that is reusable and that will allow the output to be customised the way that I originally attempted!

Comments (0)

Skip to main content