Surprisingly there is very little information about UI Hints and Display templates for ASP.net MVC 3, so I thought I would share what I have learned.
What are Display Templates?
Display Templates are lovely features of ASP.net MVC 3 that allow you to have a common formatting for certain properties of your objects. For example, take the belowp roperty (which should be located in your models folder)
[DataType(DataType.ImageUrl)]
[UIHint(“ImageUrl”)]
[Display(Name = “Photo”)]
public string Photo { get; set; }
Everything looks like a standard property, UIHint property. It would correspond to the Display Template (which is below, it would be name “ImageUrl.cshtml” and would be located in your Views/Shared/DisplayTemplates folder)
@model string
<img style=”display: block;” src=”@Model” alt=”” align=”right” />
What does the UI Hint do?
The UI Hint tells ASP.net MVC 3 to always display the Photo property using the formatting in the ImageUrl.cshtml file. That way everything is nice, clean and using much less code.
How do you call UI Hints and Display Templates?
Just use the Html.DisplayFor command, for example the Display template below would look like this in Visual Studio 2010
@Html.DisplayFor(xx => xx.Photo)
and would render as
<img style=”display: block;” src=”/img/Photos/Photo123.png” alt=”” align=”right” />
in the browser, allowing you to keep formatting and style consistent across your entire site with very little effort.
|
Written By Steve French |
Leave a Reply