Published: 09 Apr 2010
By: Brian Mains

The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we'll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.

Contents [hide]

The ASP.NET MVC 2 Series

  • Introduction to ASP.NET MVC 2.0 In this article, we'll begin examining the new features of ASP.NET MVC 2.0 by comparing what ASP.NET MVC offers against its predecessor, ASP.NET web forms.
  • ASP.NET MVC 2.0 User Interfaces The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we'll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.
  • ASP.NET MVC 2.0 Using Multiple Actions Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Templating Templating is now in the ASP.NET MVC 2.0 framework, for .NET framework 3.5 and 4.0. We are going to take a look at these features.
  • ASP.NET MVC 2.0 Attributes An overview of ASP.NET MVC 2.0 Attributes.
  • ASP.NET MVC 2.0 Validation An overview of validation in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Areas A look at ASP.NET MVC 2.0 Areas.
  • ASP.NET MVC 2.0 and AJAX Part 1 ASP.NET MVC makes working with AJAX really easy; it's quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we'll see that all here soon.
  • ASP.NET MVC 2.0 and AJAX Part 2 In this article, we are going to look at how you can utilize AJAX in your views, and utilize a concept called unobtrusive JavaScript to take advantage of a variety of situations. ASP.NET MVC provides AJAX features very easily as we previously saw, but this comes with a caveat, and it has mostly to do with the planning of the implementation. We’re going to examine these concerns in this article.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 1 In this article, we'll examine using the ADO.NET Entity Framework (ADO.NET EF). The 4.0 version has received some major upgrades, with some major API enhancements and fixes for most of the pain points within the designer.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 2 Out of the .NET framework 4.0 comes many great enhancements, the ADO.NET entity framework (ADO.NET EF) is among the top. The framework has improved upon some of the previous bugs (in version 1), as well as enhanced the API, including many new LINQ-to-SQL-like improvements. We're going to examine using these API features to create a generic version of of a data repository.
  • Complexity in ASP.NET MVC, Part 1: Dealing With Large Models At times, every developer has a web forms page or MVC view that ends up getting pretty complex, for various reasons. Whether it pulls in and integrates a lot of data (such as a portal page) or allows users to edit a lot of information, applications require data, and the amount of data grows over time. It’s a simple reality. We’re going to examine what a larger ASP.NET MVC view looks like, and some actions we can take to keep the model instantiation code as slim as possible.
  • Complexity in ASP.NET MVC, Part 2: Plan your AJAX Carefully Brian Mains discusses management of Ajax requests in ASP.NET MVC.
  • Using DI Containers in ASP.NET MVC How to use Dependency Injection containers in ASP.NET MVC.
  • Using Microsoft Unity in ASP.NET MVC Brian Mains continues his asp.net series with the unity application block.
  • Introduction

    In ASP.NET web forms and MVC, the UI goes through a rendering process. In web forms, the Page class uses a rendering process to translate a control hierarchy into HTML content for the browser. The code-behind file exposes properties and methods that affect the control's state, and the final representation of each control is what gets rendered to the browser. The page lifecycle also affects this process.

    ASP.NET MVC changes this process fundamentally. Rather than dealing with a control hierarchy, MVC views render directly in a top-to-bottom fashion, similar to how ASP used to work. The core difference between ASP and ASP.NET MVC is that the business logic is separate from the view, and is not intertwined. Each view also has a model, a property directly accessible called "Model" that contains the data returned from the controller, as a way to directly reference the data specific to that view. You will see me refer to models within this article, and every reference to it refers to this process.

    The way to construct a user interface can be a big change to most developers. For instance, in web forms, if you wanted to programmably add a style sheet to the HEAD element, a developer can put code to do this in the Load event handler. But in MVC, a style sheet can only be injected into the view at the time the HEAD element is being rendered; it can't be referenced directly as an object.

    Creating the UI

    A UI still uses similar constructs to web forms. It has a @Page directive with the same settings (though the code-behind reference points to a standard ASP.NET MVC class). It still uses markup and mixes in server-side code. But to make the entire server-side process easier, rather than using controls, MVC uses the HtmlHelper class. What used to be a control is now a method of the HtmlHelper class. For instance, to render a textbox in the browser, instead of using a control, a textbox can be written using the following code.

    <%= Html.TextBox(“Control”).ToHtmlString() %>

    This statement renders an <input type="text"> element directly to the response stream. Note that the ToHtmlString method call; this is a new breaking change in ASP.NET MVC 2 as each helper returns this instead of a string directly. However, you can omit this if you like, and the code will work the same (the method will be called implicitly).

    The following is a sample UI using these helpers:

    Listing 1: Sample Form using MVC

    Each one of these methods returns a string that represents the HTML of the control. Using these methods allows for the in-built features of MVC to work, as MVC uses certain schemes to link features together. You can certainly define the HTML for the control directly, if you like.

    New “For” Suffix Helpers

    With MVC 2 comes a whole new group of methods suffixed with "For", such as TextBoxFor, CheckBoxFor, etc. These methods use a lambda to select the property within the model to use to display the UI. For instance, Html.TextBoxFor(i => i.FirstName) extracts the value of the first name of the model.

    Listing 2: Using For Extension Methods

    This does two things: the first is it renders the underlying HTML element with the model's intrinsic value. Additionally, the ID and name of the element use the text from the lambda expression supplied here as the name (ScenarioNumber and Description in this example). These methods can make it very convenient to render content directly to the model, and also help to hook up model binding (explained later).

    Data Annotations

    I mentioned these new methods for rendering content extract its value from the data model. The reality is that it does more than this. By using a lambda, the ASP.NET MVC framework also looks for any data annotations on a property. A data annotation is an attribute that you specify on the model. These annotations control how the helper methods work in various ways. For instance, take a look at the following sample property:

    Listing 3: Data Annotation Support

    So here, our model class has a BoolValue property with two annotations, the latter one for validation (a subject of a future article), and the former one for storing the display name of the field. The display name attribute comes in handy if you want to use the next extension method to write out a <label> element for this property as in:

    Listing 4: Rendering the Label

    This renders a label element with our "Boolean Val" name, followed by a checkbox with the model value name.

    A Final Model Binding Example

    It's best to just look at an example of the entire process and the process of how model binding works. Let's walk through a sample setup form using these constructs. To start, we must have a controller that points to our view. Below is a sample view that has a method to return the view by referencing a URL of SampleForm/ForIndex. The next action method responds to a form post only.

    Listing 5: Sample Controller

    This controller is simple enough; primarily, keep an eye on the initial values entered. The model used for the ForIndex view is the SampleFormTestClass that contains some data annotations; a lot of the data annotations tend to be validation-specific, a topic too big for this article.

    Listing 6: Sample Model

    The UI uses the properties within this model using the following form example. I'm going to break it up into pieces. The first piece is the definition of the form; forms can be specified using one of the syntaxes below.

    Listing 7: Defining a Form

    Everything within the form tags is posted back to the server to our ForIndex action method marked with a [HttpPost] attribute. The first to render is a label and checkbox combination for our BoolValue property. Remember that it had a DisplayName attribute, which renders the text "Boolean Val" for the label, instead of the actual property name (by default).

    Listing 8: Setting Up a Label and CheckBox

    Alternatively, if you like radio buttons for yes/no fields, the following is also an option. While no radiobuttonlist control exists, each radio button can map to a boolean or other type property (here a string) to render the radio button list. The second parameter is not the text of the radio button; actually, it's the value to match to actually select the item in the list (its associated value). The second radio button is selected since the model has a no value.

    Listing 9: Setting Up a Radio Button List

    We covered rendering textboxes and text areas to the screen; additionally below is a hidden field and a password box. A word of caution with these controls; if you have a specialized data type (like a DateTime or an integer) that is being represented by a text box, there isn't any implicit error checking for these types of data values. Validation can be applied to the value to prevent this; if for some reason an invalid value slips through, the value is omitted and the default value is used (a default date of 1/1/0001, for example).

    Listing 10: Setting Up Text Elements

    The standard list types are also supported; below are methods to render a drop down list and list box using a list of data (can be static or data bound), and extracting the underlying value to supply as the default selected item. This may be a typical operation to occur within the controller, rather than the UI, but I put it in the UI for the example's sake.

    Listing 11: Setting Up Lists

    Not every HTML element has an associated HTML helper method. For instance, any type of button does not have a ButtonFor method. No support for linkbuttons exist too, which is a substantial change (because internally of the way that the MVC framework differs from web forms).

    The final UI looks like the following:

    Figure 1: The Sample Form

    The Sample Form

    I tweaked the original values toggling the AltBoolValue and BoolValue ui controls, changing the combo selection, and creating an invalid date, which led to the following values being posted back.

    Figure 2: The Posted Values

    The Posted Values

    Here is the greatest feature about the model binding process; by using our lambda expressions, the values posted back within the form automatically get mapped to the class's properties, when the class is the parameter of the action method. So, since the fields posting back are related to our model class, MVC automatically supplied these form values to our object, and I don't have to manually perform this task. This process is customizable by creating a custom model binder if you like, but that is a subject for another day too.

    If you don't like using the object reference directly in this way, and want more control over the process, the alternative is to specify a FormCollection collection as the parameter of the action method, which contains all of the form values within the form that posted back (and any other form related value that may come over too). This way, you can have more control over the data. The UpdateModel or TryUpdateModel methods can be used to apply the form collection to a model object too, as an added convenience.

    Conclusion

    ASP.NET MVC is powerful. Once you understand the building blocks mentioned in this article, you can begin to create complex UI's. The key is understanding how MVC takes away the control lifecycle/API/hierarchy architecture and uses an inline rendering approach, as well as understanding the separation of logic that MVC utilizes.

    We looked at a variety of HTML helper methods used to construct UI's and make the UI construction process easier, as well as alternative ways we can pass this information around. MVC can take a form's values and apply them directly to an object. It's good to understand the basics before you jump right into building a complex UI, as building complex UI's need care and well-thought-out planning. We will be examining this in future articles.

    The ASP.NET MVC 2 Series

  • Introduction to ASP.NET MVC 2.0 In this article, we'll begin examining the new features of ASP.NET MVC 2.0 by comparing what ASP.NET MVC offers against its predecessor, ASP.NET web forms.
  • ASP.NET MVC 2.0 User Interfaces The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we'll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.
  • ASP.NET MVC 2.0 Using Multiple Actions Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Templating Templating is now in the ASP.NET MVC 2.0 framework, for .NET framework 3.5 and 4.0. We are going to take a look at these features.
  • ASP.NET MVC 2.0 Attributes An overview of ASP.NET MVC 2.0 Attributes.
  • ASP.NET MVC 2.0 Validation An overview of validation in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Areas A look at ASP.NET MVC 2.0 Areas.
  • ASP.NET MVC 2.0 and AJAX Part 1 ASP.NET MVC makes working with AJAX really easy; it's quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we'll see that all here soon.
  • ASP.NET MVC 2.0 and AJAX Part 2 In this article, we are going to look at how you can utilize AJAX in your views, and utilize a concept called unobtrusive JavaScript to take advantage of a variety of situations. ASP.NET MVC provides AJAX features very easily as we previously saw, but this comes with a caveat, and it has mostly to do with the planning of the implementation. We’re going to examine these concerns in this article.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 1 In this article, we'll examine using the ADO.NET Entity Framework (ADO.NET EF). The 4.0 version has received some major upgrades, with some major API enhancements and fixes for most of the pain points within the designer.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 2 Out of the .NET framework 4.0 comes many great enhancements, the ADO.NET entity framework (ADO.NET EF) is among the top. The framework has improved upon some of the previous bugs (in version 1), as well as enhanced the API, including many new LINQ-to-SQL-like improvements. We're going to examine using these API features to create a generic version of of a data repository.
  • Complexity in ASP.NET MVC, Part 1: Dealing With Large Models At times, every developer has a web forms page or MVC view that ends up getting pretty complex, for various reasons. Whether it pulls in and integrates a lot of data (such as a portal page) or allows users to edit a lot of information, applications require data, and the amount of data grows over time. It’s a simple reality. We’re going to examine what a larger ASP.NET MVC view looks like, and some actions we can take to keep the model instantiation code as slim as possible.
  • Complexity in ASP.NET MVC, Part 2: Plan your AJAX Carefully Brian Mains discusses management of Ajax requests in ASP.NET MVC.
  • Using DI Containers in ASP.NET MVC How to use Dependency Injection containers in ASP.NET MVC.
  • Using Microsoft Unity in ASP.NET MVC Brian Mains continues his asp.net series with the unity application block.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Brian Mains

    Brian Mains is an application developer consultant with Computer Aid Inc. He formerly worked with the Department of Public Welfare. In both places of business, he developed both windows and web applications, small and large, using the latest .NET technologies. In addition, he had spent many hou...

    This author has published 73 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
    A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    Exception Handling and .Net (A practical approach)
    Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.
    jQuery Mobile Pages
    Brian Mains explains how to create pages with the jQuery Mobile framework.

    You might also be interested in the following related blog posts


    Understanding the MvcRouteHandler and MvcHandler in ASP.NET MVC read more
    Interviewing Javier Lozano 7 Nov 2009 (tonight) at 8pm PST read more
    Html Encoding Nuggets With ASP.NET MVC 2 read more
    MVC or Web Forms? A Dying Question read more
    Adding users to a TFS project when youre not on the domain read more
    Creating a Filtering User Interface With jQuery In a Web Forms Application: Part 2 read more
    Creating a Filtering User Interface With jQuery In a Web Forms Application: Part 1 read more
    MvcContrib working on Portable Areas read more
    End to End MVC application read more
    A proposed introduction... read more
    Top
     
     
     

    Please login to rate or to leave a comment.

    Free Agile Project Management Tool from Telerik
    TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.