Introduction to Templates in ASP.NET MVC 2 Screen cast
I have recorded some screen casts during the last week for
Microsoft, one is was published today on Channel 9 (The
Screen cast is in Swedish, I will eventually try to record
screen casts also in English, but when that happens, I don’t
now). You can found the screen cast here:
http://channel9.msdn.com/posts/MSDNSweden/Introduktion-till-Template-i-ASPNET-MVC-2/
For those who can’t understand Swedish, here is a short summary of the screen cast.
With ASP.NET MVC version 2.0 we can use templates. It will
help us rendering forms etc out form the Model we passed to
the View. We can easy modify templates to satisfy our needs.
The simples way to use the Template feature is to use the
Html’s DisplayForModel method:
<%= Html.DisplayForModel() %>
This method will iterate through the
ViewData.ModelMetadata.Properties to render the Model. The
ModelMetadata hold information about the model, such as
properties etc. The result will remind us about the
DetailView control shipped with ASP.NET 2.0, but will put
the name of the property at top, and then a new line with
the value of the property, like this:
FirstName
John
LastName
Doe
There is also a method to render a editable from,
EditorForModel. By default the methods will use a default
template, we can easy override the template. We do that by
adding a ASP.NET MVC User Control to the
~/Views/ControllerName/DisplayTemplates or EditTemplates
folder. If you want to override how a String should be
“rendered”, then you simply add a String.ascx file to the
Templates folders, here is an example of a DisplayTemplate:
<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl"%>
<i><%= Html.Encode(Model) %></i>
The above template will make the value of the rendered
property to use italic:
FirstName
John
LastName
Doe
We can do several more stuffs with template, for more information check out the following blog post from Brad Wilson:
You can find me on twitter: http://www.twitter.com/fredrikn