Rendering a Form in ASP.NET MVC Using HTML Helpers

The ASP.NET MVC framework includes helper methods that provide an easy way to render HTML in a view. This topic explains how to work with the most frequently used HTML helpers. The last section shows an example that incorporates the HTML helpers described in this topic.

Available HTML Helpers

The following list shows some of the currently available HTML helpers. The helpers listed with an asterisk (*) are demonstrated in this topic.

  • ActionLink — Links to an action method.

  • BeginForm * — Marks the start of a form and links to the action method that renders the form.

  • CheckBox * — Renders a check box.

  • DropDownList * — Renders a drop-down list.

  • Hidden — Embeds information in the form that is not rendered for the user to see.

  • ListBox — Renders a list box.

  • Password — Renders a text box for entering a password.

  • RadioButton * — Renders a radio button.

  • TextArea — Renders a text area (multi-line text box).

  • TextBox * — Renders a text box.

Using the BeginForm Helper

The BeginForm helper marks the start of an HTML form and renders as an HTML form element. The BeginForm helper method has several overrides. The version of the BeginForm helper shown in the following example takes two parameters, the names of the action method and the controller to submit the form. The BeginForm helper implements the IDisposable interface, which enables you to use the using keyword (Using in Visual Basic), similar to ASP.NET AJAX usage.

The following example shows how to use the BeginForm helper in a using pattern.

<% Using Html.BeginForm("HandleForm", "Home") %>
    <!-- Form content goes here -->
<% End Using %>
<% using(Html.BeginForm("HandleForm", "Home")) %>
<% { %>
    <!-- Form content goes here -->
<% } %>

You can also use the BeginForm helper declaratively. The difference between using BeginForm declaratively and using an HTML form tag is that BeginForm assigns default value for the action method and action attributes, which simplifies the markup. The following example uses declarative markup to mark the start and ending of a form.

<% Html.BeginForm() %>
    <!-- Form content goes here -->
<% Html.EndForm() %>
<% Html.BeginForm(); %>
    <!-- Form content goes here -->
<% Html.EndForm(); %>

Using the CheckBox Helper

The CheckBox helper method renders a check box that has the name that you specify. The rendered control returns a Boolean value (true or false). The following example shows markup for the CheckBox helper method.

<%= Html.CheckBox("bookType") %>

Using the DropDownList Helper

The DropDownList helper renders a drop-down list. In its simplest form, DropDownList takes one parameter, the name of the ViewData key whose value is of type SelectList and that contains the option values for the drop-down list. The MVC framework uses the ModelState property of ViewData to determine the selected value. If the ModelState property is empty, the framework looks for an item whose Selected property is set.

The following example shows markup for the DropDownList helper method.

<%= Html.DropDownList("pets") %>

Note

Both the DropDownList and ListBox helpers accept either a SelectList or MultiSelectList object.

The following code is a part of an Index action method in which values are added to a List object. The List object is passed to an instance of SelectList, which is then added to the ViewData object.

Dim petList As List(Of String) = New List(Of String)
petList.Add("Dog")
petList.Add("Cat")
petList.Add("Hamster")
petList.Add("Parrot")
petList.Add("Gold fish")
petList.Add("Mountain lion")
petList.Add("Elephant")

ViewData("pets") = New SelectList(petList)
List<string> petList = new List<string>();
petList.Add("Dog");
petList.Add("Cat");
petList.Add("Hamster");
petList.Add("Parrot");
petList.Add("Gold fish");
petList.Add("Mountain lion");
petList.Add("Elephant");

ViewData["Pets"] = new SelectList(petList);

Using the RadioButton Helper

The RadioButton helper method renders a radio button. In its simplest form, the method takes three parameters: the name of the control group, the option value, and a Boolean value that determines whether the radio button is selected initially. The following markup shows markup for the RadioButton helper method.

Select your favorite color:<br />
<%= Html.RadioButton("favColor", "Blue", true) %> Blue <br />
<%= Html.RadioButton("favColor", "Purple", false)%> Purple <br />
<%= Html.RadioButton("favColor", "Red", false)%> Red <br />
<%= Html.RadioButton("favColor", "Orange", false)%> Orange <br />
<%= Html.RadioButton("favColor", "Yellow", false)%> Yellow <br />
<%= Html.RadioButton("favColor", "Brown", false)%> Brown <br />
<%= Html.RadioButton("favColor", "Green", false)%> Green

Using the TextBox Helper

The TextBox helper method renders a text box that has the specified name. The following markup shows markup for the TextBox helper method.

Enter your name: <%= Html.TextBox("name") %>

Example Application

The following example is a complete example from which the previous examples where taken. The Index page displays a form that implements HTML helper methods. When the user submits the form, the form is handled by the HandleForm action method, which generates a view that displays the information that the user submitted.

The following example shows the HomeController class.

<HandleError()> _
Public Class HomeController
    Inherits System.Web.Mvc.Controller

    Function Index() As ActionResult
        ViewData("Message") = "Welcome to ASP.NET MVC!"

        Dim petList As List(Of String) = New List(Of String)
        petList.Add("Dog")
        petList.Add("Cat")
        petList.Add("Hamster")
        petList.Add("Parrot")
        petList.Add("Gold fish")
        petList.Add("Mountain lion")
        petList.Add("Elephant")

        ViewData("pets") = New SelectList(petList)

        Return View()
    End Function

    Function About() As ActionResult
        Return View()
    End Function

    Public Function HandleForm(ByVal name As String, ByVal favColor As String, ByVal bookType As Boolean, ByVal pets As String) As ActionResult
        ViewData("name") = name
        ViewData("favColor") = favColor
        ViewData("bookType") = bookType
        ViewData("pet") = pets

        Return View("FormResults")
    End Function
End Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcHtmlHelpers.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            List<string> petList = new List<string>();
            petList.Add("Dog");
            petList.Add("Cat");
            petList.Add("Hamster");
            petList.Add("Parrot");
            petList.Add("Gold fish");
            petList.Add("Mountain lion");
            petList.Add("Elephant");

            ViewData["Pets"] = new SelectList(petList);

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult HandleForm(string name, string favColor, Boolean bookType, string pets)
        {
            ViewData["name"] = name;
            ViewData["favColor"] = favColor;
            ViewData["bookType"] = bookType;
            ViewData["pet"] = pets;

            return View("FormResults");
        }
    }
}

The following example shows the Index view.

<h2><%= Html.Encode(ViewData("Message")) %></h2>
<br /><br />
<% Using Html.BeginForm("HandleForm", "Home")%>
    Enter your name: <%= Html.TextBox("name") %>
    <br /><br />
    Select your favorite color:<br />
    <%= Html.RadioButton("favColor", "Blue", true) %> Blue <br />
    <%= Html.RadioButton("favColor", "Purple", false)%> Purple <br />
    <%= Html.RadioButton("favColor", "Red", false)%> Red <br />
    <%= Html.RadioButton("favColor", "Orange", false)%> Orange <br />
    <%= Html.RadioButton("favColor", "Yellow", false)%> Yellow <br />
    <%= Html.RadioButton("favColor", "Brown", false)%> Brown <br />
    <%= Html.RadioButton("favColor", "Green", false)%> Green 
    <br /><br />
    <%=Html.CheckBox("bookType")%> I read more fiction than non-fiction.<br />
    <br /><br />
    My favorite pet: <%=Html.DropDownList("pets")%>
    <br /><br />
    <input type="submit" value="Submit" />
<% End Using%>
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<br /><br />
<% using(Html.BeginForm("HandleForm", "Home")) %>
<% { %>
    Enter your name: <%= Html.TextBox("name") %>
    <br /><br />
    Select your favorite color:<br />
    <%= Html.RadioButton("favColor", "Blue", true) %> Blue <br />
    <%= Html.RadioButton("favColor", "Purple", false)%> Purple <br />
    <%= Html.RadioButton("favColor", "Red", false)%> Red <br />
    <%= Html.RadioButton("favColor", "Orange", false)%> Orange <br />
    <%= Html.RadioButton("favColor", "Yellow", false)%> Yellow <br />
    <%= Html.RadioButton("favColor", "Brown", false)%> Brown <br />
    <%= Html.RadioButton("favColor", "Green", false)%> Green 
    <br /><br />
    <%= Html.CheckBox("bookType") %> I read more fiction than non-fiction.<br />
    <br /><br />
    My favorite pet: <%= Html.DropDownList("pets") %>
    <br /><br />
    <input type="submit" value="Submit" />
<% } %>

The following example shows the FormResults view.

<h2>FormResults</h2>
<p>
Your name: <b><%=Html.Encode(ViewData("name"))%></b>
</p>
<p>
Your favorite color: <b><%=Html.Encode(ViewData("favColor"))%></b>
</p>
<%  If (ViewData("bookType").Equals(True)) Then%>
<p>You read more <b>fiction</b> than non-fiction.</p>
<% Else%>
<p>You read more <b>non-fiction</b> than fiction.</p>
<% End If%>
Your favorite pet: <b><%=Html.Encode(ViewData("pet"))%></b>
<h2>FormResults</h2>
<p>
Your name: <b><%= Html.Encode(ViewData["name"])%></b>
</p>
<p>
Your favorite color: <b><%= Html.Encode(ViewData["favColor"]) %></b>
</p>
<% if (ViewData["bookType"].Equals(true))
   { %>
<p>You read more <b>fiction</b> than non-fiction.</p>
<% }
   else
   { %>
<p>You read more <b>non-fiction</b> than fiction.</p>
<% } %>
Your favorite pet: <b><%= Html.Encode(ViewData["pet"]) %></b>

See Also

Concepts

Views and UI Rendering in ASP.NET MVC Applications