Tuesday, June 16, 2015

Introduction to Templates in ASP.NET MVC

Introduction to Templates

Html.Display
  • String based: <%= Html.Display(“PropertyName”) %>
  • Expression based: <%= Html.DisplayFor(model => model.PropertyName) %>
  • Model: <%= Html.DisplayForModel() %>
1
2
3
4
5
public class Contact {
    public string FirstName { getset; }
    public string LastName { getset; }
    public int Age { getset; }
}
1
2
3
public ViewResult Details([DefaultValue(0)] int id) {
    return View(contacts[id]);
}
1
2
3
4
5
6
7
<%@ Page Language="C#"
    MasterPageFile="~/Views/Shared/Site.master"
    Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
    <%= Html.DisplayForModel() %>
</asp:Content>
Example web page for DisplayForModel
Html.Editor
  • String based: <%= Html.Editor(“PropertyName”) %>
  • Expression based: <%= Html.EditorFor(model => model.PropertyName) %>
  • Model: <%= Html.EditorForModel() %>
Example web page for EditorForModel
What’s Really Happening?
1
2
3
4
<% foreach (var prop in ViewData.ModelMetadata.Properties) { %>
    <div class="display-label"><%= prop.GetDisplayName() %></div>
    <div class="display-field"><%= Html.Display(prop.PropertyName) %></div>
<% } %>
1
<%= Html.Encode(Model) %>
Overriding Templates
Screenshot of Views showing DisplayTemplates folder and String.ascx
1
2
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.Encode(Model) %> <em>Hello there!</em>
Updated DisplayForModel view using our custom template
Wrapping Up


No comments:

Post a Comment