ASP.NET MVC 2 Beta - Strongly Typed UI Helpers

Posted by: Malcolm Sheridan , on 12/18/2009, in Category ASP.NET MVC
Views: 22089
Abstract: The following article demonstrates how to use ASP.NET MVC 2 Beta’s strongly typed UI helpers.
ASP.NET MVC 2 Beta - Strongly Typed UI Helpers
 
ASP.NET MVC 2 Beta Preview 1 has been announced recently. One of the nicest features to come out of this release is the ability to have strongly typed UI helpers. This means in your view this enables you to use strongly-typed lambda expressions when referencing the views template model object. This makes your code more readable in my opinion, and also can reduce the number of errors as you now have compile time checking of views. This example was built using Visual Studio 2010 beta 2. You can download it here.
To demonstrate this I’ve created a class that will represent my model:

 

C#
 
public class Employee
{
public int Id { get; set; }
      public string GivenName { get; set; }
      public string Surname { get; set; }
      public DateTime DateOfBirth { get; set; }
      public bool Permanent { get; set; }
      public double Salary { get; set; }
}
 
VB.NET
 
Public Class Employee
Private privateId As Integer
Public Property Id() As Integer
      Get
            Return privateId
      End Get
      Set(ByVal value As Integer)
            privateId = value
      End Set
End Property
       Private privateGivenName As String
       Public Property GivenName() As String
             Get
                   Return privateGivenName
             End Get
             Set(ByVal value As String)
                   privateGivenName = value
             End Set
       End Property
       Private privateSurname As String
       Public Property Surname() As String
             Get
                   Return privateSurname
             End Get
             Set(ByVal value As String)
                   privateSurname = value
             End Set
       End Property
       Private privateDateOfBirth As DateTime
       Public Property DateOfBirth() As DateTime
             Get
                   Return privateDateOfBirth
             End Get
             Set(ByVal value As DateTime)
                   privateDateOfBirth = value
             End Set
       End Property
       Private privatePermanent As Boolean
       Public Property Permanent() As Boolean
             Get
                   Return privatePermanent
             End Get
             Set(ByVal value As Boolean)
                   privatePermanent = value
             End Set
       End Property
       Private privateSalary As Double
       Public Property Salary() As Double
             Get
                   Return privateSalary
             End Get
             Set(ByVal value As Double)
                   privateSalary = value
             End Set
       End Property
End Class
 
VB.NET 10.0 (as shared by Rory Becker)

Public Class Employee
    Public Property Id() As Integer
    Public Property GivenName As String
    Public Property Surname As string
    Public Property DateOfBirth As DateTime
    Public Property Permanent As Boolean
    Public Property Salary As Double
End Class
In order to use the new strongly typed UI feature, your view will look something like this:
 
<h2>Employee</h2>
    <% using (Html.BeginForm()) {%>
        <fieldset>
            <legend>Fields</legend>           
            <p>
                <%= Html.LabelFor(o => o.GivenName) %>
                <%= Html.EditorFor(o => o.GivenName) %>
            </p>
            <p>
                <%= Html.LabelFor(o => o.Surname) %>
                <%= Html.EditorFor(o => o.Surname) %>
                <%= Html.ValidationMessage("Surname", "*") %>
            </p>
            <p>
                <%= Html.LabelFor(o => o.DateOfBirth) %>
                <%= Html.EditorFor(o => o.DateOfBirth)%>          
                <%= Html.ValidationMessage("DateOfBirth", "*") %>
            </p>
            <p>
                <%= Html.LabelFor(o => o.Permanent) %>
                <%= Html.EditorFor(o => o.Permanent) %>
                <%= Html.ValidationMessage("Permanent", "*") %>
            </p>
            <p>
                <%= Html.LabelFor(o => o.Salary) %>
                <%= Html.EditorFor(o => o.Salary)%>
                <%= Html.ValidationMessage("Salary", "*") %>
            </p>
            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>
    <% } %>
Notice these two lines of code above?
 
<%= Html.LabelFor(o => o.Surname) %>
<%= Html.EditorFor(o => o.Surname) %>
 
These are part of the new HtmlHelpers class. The Html.LabelFor() helper method above generates <label for="GivenName">Given Name:</label> HTML markup.
 
The Html.EditorFor() helper method accepts any type of data type. It works out at runtime the type of HTML to be rendered for the model property. So for GivenName it generates <input type=”text” id=”GivenName” />
 
Html.EditorFor() also allows you to pass in more complex data types. By default, it will loop over the controls and render a <label> and <input /> element over each property. So if you didn’t care about the HTML markup being generated, you could just pass in the Employee object like this:
 
<h2>Employee</h2>
    <% using (Html.BeginForm()) {%>
        <fieldset>
            <legend>Fields</legend>
            <p>
                <%= Html.EditorFor(e => e) %>
            </p>
            <p>
                <input type="submit" value="Save" />
            </p>       
        </fieldset>
    <% } %>
 
That way there’s less code, but you lose control over the HTML being rendered. As well as Html.LabelFor() and Html.EditorFor() an updated MVC futures release adds additional Html.TextBoxFor(), Html.TextAreaFor(), Html.DropDownListFor(), Html.HiddenFor(), and Html.ValidationMessageFor() helper methods to your arsenal.
 
This is just another small part of ASP.NET MVC 2 Beta Preview 1. Stay tuned for more to come! The entire source code of this article can be downloaded over here
Give me a +1 if you think it was a good article. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Rory Becker on Friday, December 18, 2009 10:38 AM
If this really is a VS2010 demo as indicated, perhaps the more compact VB10 syntax would make for an easier read.

http://codepaste.net/h13w2x
Comment posted by Carol on Saturday, December 19, 2009 1:34 AM
Thanks Rory. The code has been updated.
Comment posted by cbrcoder on Sunday, December 20, 2009 7:25 AM
Using "privateSalary" as variable name sounds extremely strange to me! I don't think it is a good practice, can you please explain why you did that ?
Comment posted by Malcolm Sheridan on Monday, December 21, 2009 5:29 PM
@cbrcoder
The VB.Net code provided in my articles is auto generated, so the naming conventions are related to the conversion process.
Comment posted by Sean on Tuesday, December 22, 2009 10:59 AM
Just FYI, the ASP.NET MVC 2.0 RC has already been released and can be downloaded here: http://www.microsoft.com/downloads/details.aspx?FamilyID=3b537c55-0948-4e6a-bf8c-aa1a78878da0&displaylang=en
Comment posted by Malcolm Sheridan on Sunday, December 27, 2009 10:17 PM
@Sean
Thanks for the update.
Comment posted by Uddhav Garkal on Thursday, April 22, 2010 2:33 AM
Thanks.
Nice article.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel