I’ve just started to learn MVC.
I know that you can create a strongly typed view in Shared/DisplayTemplates, then after returning a list from the controller, you can do @Html.DisplayForModel() and it will use this as a template for the entire list.
However, what if I don’t always want the model to be built in the way I’ve specified in this DisplayTemplate? How can I create different display templates?
The obvious way seems to be to create a template for each object, then do something like…
@foreach(var item in Model)
{
@Html.DisplayFor(x=>x, "AlternativeTemplate")
}
..but as you’ve now got the foreach, it doesn’t seem as elegant.
You are right, you can use the DisplayForModel overload that takes a String param for the template name. http://msdn.microsoft.com/en-us/library/ee430910(v=vs.98).aspx
You just have to have the template defined under Views/Shared/DisplayTemplates with the exact name as given in the String.