Dec 18

The MVC platform – the HtmlHelper class (part III)

Posted in ASP.NET MVC      Comments Off on The MVC platform – the HtmlHelper class (part III)

After the slight detour for introducing validation support, it’s time to go back to the helpers which you can use for generating HTML controls from your views. I think that the second post on the HtmlHelper class should have been more than enough for understanding how things work, so in this post I’ll just jump into a description of the remaining methods exposed by the InputExtensions static class.

Besides the TextBox method (which, as we’ve seen, is  used for generating simple textboxes), you’ll also find:

  • CheckBox: used fore generating checkboxes (ie, HTML elements similar to <input type=”checkbox”>);
  • Hidden: used for inserting hidden textboxes (ie, HTML INPUT elements with the type set to hidden);
  • Password: ok, you’ve guessed it! It’s used for generating input fields that will be used for entering passwords (ie, this method inserts <input type=”password”> elements on the page);
  • RadioButton: used for inserting radio buttons elements on the page (ie, this method inserts <input type=”radio”> on the page).

Lets build a form that shows how to use some of these methods. To do that, I’ll just change the code that exists in the Index view you get whenever you create a new MVC project form the VS template. Here’s what I’ve added:

<form method="post" action="<%= Url.Action("HandleFormData","Home") %>">
      <label for="name">Name:</label><%= Html.TextBox( "name" ) %>
      <%= Html.ValidationMessage("name","*")%>
      <br />
      <label for="password">Password:</label><%= Html.Password( "password" ) %>
      <%= Html.ValidationMessage("name","*")%>
      <br />
      <label for="male">Male:</label>
      <%= Html.RadioButton("sex", "male",  new {id = "male"}) %>
      <label for="female">Female:</label>
      <%= Html.RadioButton("sex", "female",  new { id = "female" })%>
      <input type="submit" id="myBt" value="Try to submit" /> <br />
      <%= Html.ValidationSummary() %>

So, what do we have here:

  • we’re using labels that are associated to each of the controls;
  • we’re setting the ID of each radio button explicitly so that we can associate a label to each option. Btw, and since we’re talking about radio buttons, notice that the previous snippet won’t select any option by default. If you need that you can use one of the overloads that sets the checked property of the control or, way better, add code that sets the ViewData dictionary of the control to the value you want (for instance, lets say you want to select male by default. Then you’d add this to the method that renders the initial form: ViewData["sex"] = "male";). Notice that the second option is better because it will let you maintain the value introduced by the user if there’s an error on the form (the first will always set the option to the predefined value and the value selected by the user will be lost). More about this on the next paragraphs;
  • we’re using yesterday’s ideas and we’re reusing the logic for validation;
  • the form ends up calling the HandleFormData action method on the Home controller.

The HandleFormData action method is responsible for performing validation on the incoming data. If everything is OK, it will simply redirect that info to another view which, in this case, will only display that info on a aspx page. Here’s the code for HandleFormData:

public ActionResult HandleFormData() {
    var name = Request.Form["name"];
    ViewData["name"] = name;
    ViewData["password"] = Request.Form["password"];
    ViewData["sex"] = Request.Form["sex"]; 

    if (String.IsNullOrEmpty(name) || name.Length < 4) {
        var state = new ModelState()
                            AttemptedValue = name
        state.Errors.Add("name must have more than 4 chars.");
        ViewData.ModelState.Add("name", state);
        return View("Index");
       return View("UntypedUserInfo");

Ok, not really the best code in the world, but it will do for this short demo. As you can see, I start by filling the view data dictionary so that the controls on the form will have the values entered by the user if there’s an error.The same view data will also be used by the UntypeduserInfo view which is only responsible for showing the info introduced by the user. here’s the code on that page:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="UntypedUserInfo.aspx.cs" Inherits="MvcDemo.Views.Home.UntypedUserInfo" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    name: <%= Html.Encode( ViewData["Name"] ) %><br />
    password: <%= Html.Encode( ViewData["Password"] ) %><br />
    sex: <%= Html.Encode( ViewData["Sex"] ) %><br />

If you’re an “experienced” ASP.NET MVC developer, you’ll be thinking that there must be a better way of doing this (and yes, I believe there is and we’ll show it in a future post), but this small sample should be more than enough to give you an idea of what you can do with the helpers.

And I believe that’s all for today. We’ll keep looking at the MVC framework on the next posts. Keep tuned!