Wednesday, July 7, 2010

Html Helper for Model Binding in MVC2

In ASP.NET MVC2, you can create a model and bind its properties to the UI by using "DisplayFor" or "LabelFor" or "EditorFor". To illustrate, let's take a look an example. For instance, if I have a model:

    public class Person {
        [DisplayName("Full Name")]
        public string FullName { get; set; }

        [DisplayName("Email Address")]
        public string Email { get; set; }

        public string Address{ get; set; }
To create an editor for the model will look like this in the old way of MVC:

        <div class="editor-label">
            Full Name 
        <div class="editor-field">
            <%=Html.TextBox("FullName") %>
            <%=Html.ValidationMessage("FullName") %>

With the new "DisplayFor", "EditorFor" and "LabelFor" etc, we can transform that code into something like this - and it will render the same way:

        <div class="editor-label">
            <%: Html.LabelFor(m => m.FullName) %>
        <div class="editor-field">
            <%: Html.TextBoxFor(m => m.FullName) %>
            <%: Html.ValidationMessageFor(m => m.FullName) %>

This code is much cleaner, flexible, easier to maintain, and validation is centralized in the business layer. So for example, if for whatever reason the label should be changed to "Name" instead of "Full Name", all we need to do is change the "DisplayName" attribute in the model declaration.

Now for the address field, we attributed "DataType(DataType.MultilineText)" to it. This will automatically render out a text area instead of a regular text box.

If we do not like the way the default template render, we can always override it. Brad Wilson has an excellent blog post series about this.

No comments: