5

I'm building an intranet and the home page is covered in widgets that show lots of different bits of data. I have a Home.cs model with various IEnumerables properties for the data required. I have been using View folder DisplayFor templates to render that data. I now come to a problem where two different lists of Staff need to be shown in two different ways.

I could use a partial view to render one of the lists or perhaps inherit the class and have a different template. Inheritance seems more work that necessary, I was wondering if anyone knows of a specific way MVC was designed to use or perhaps just a prefered solution by anyone?

Tod
  • 2,070
  • 21
  • 27
  • Are they associated with different controllers? If so you can have a `DisplayTemplates` folder associated each controller. –  Apr 16 '15 at 08:47

2 Answers2

2

Just have two different templates, then specify the template to use for each using this overload of DisplayFor:

@Html.DisplayFor(m => m.StaffList, "StaffTemplate1")

@Html.DisplayFor(m => m.StaffList, "StaffTemplate2")
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • I prefer this answer for the only reason of Maintainability, it's easier to see in the on-page code why a different template is being used. Also this suffers from lack of enumerable support: http://stackoverflow.com/questions/25333332/correct-idiomatic-way-to-use-custom-editor-templates-with-ienumerable-models-in But in all fairness using this and putting in dirty, dirty for each loops is easier than trying to fix the enumerable issue. – Tod Apr 16 '15 at 09:52
2

If you want to use different Display templates for each staff list you can either specify the template to use in the DisplayFor call:

@Html.DisplayFor(m => m.StaffListOne, "StaffTemplateOne");
@Html.DisplayFor(m => m.StaffListTwo, "StaffTemplateTwo");

Or you can add a UIHint attribute to the model properties:

[UIHint("StaffTemplateOne")]
public IEnumerable<Staff> StaffListOne { get;set; }

[UIHint("StaffTemplateTwo")]
public IEnumerable<Staff> StaffListTwo { get;set; }
Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
  • Thank you for your contribution too, UIHint also suffers from lack of Enumerable support. I also looked into [DisplayType("CustomType")] to trick the render into using another template, apparently that USED to work with Enumerables but no longer in MVC 5. Hopefully an answer will come with VNext. – Tod Apr 16 '15 at 09:56