html helpers in mvc part 2 | built-in helper methods

html helpers in mvc part 2

Overview of built-in helper methods in ASP.NET MVC

In this ASP.NET MVC tutorial for html helpers in MVC we will see following types of built-in helper methods in MVC :

  • Form helpers methods
  • Input helper methods
  • Select helper methods

Form helper methods :

In MVC built-in form helper methods can be used to create form elements.

Using the helper methods to generate html elements like form and input is not compulsory. If you prefer, you can code them using static html tags and populate values using view data or view model objects.

The html that is generated from the helper is clean and there are no special attribute values or sneaky tricks that you have to use them. But they make it easy to ensure that the html is in sync with the application so that, for example, changes in routing configuration will be reflected automatically in your forms.

To demonstrate using built-in form helper methods lets create an example app.

Create a new MVC web application using empty template and Add a class Person.cs in Models folder.

Create new controller named HomeController and add following action methods to HomeController to use model objects.

I have created the Views/Shared folder and added a layout file called _Layout.cshtml with the contents shown :

Two of the most useful (and most commonly used) helpers are Html.BeginForm and Html.EndForm.

These helpers create HTML form tags and generate a valid action attribute for the form that is based on the routing mechanism for the application.

Create a view CreatePerson.cshtml and set its content as following :

Notice that I had to treat the call to the helper methods as a C# statements.

A much more common approach (and convenient) is shown in the following code, which wraps the call to the BeginForm helper method in a using expression.

At the end of the using block, the .NET runtime calls the Dispose method on the object returned by the BeginForm method, which calls the EndForm method for you.

The BeginForm helper method has following overloads :

Overload Description
BeginForm() Creates a form which posts back to the action method it originated from
BeginForm(action, controller Creates a form which posts back to the action method and controller, specified as strings
BeginForm(action, controller, method) As for the previous overload, but allows you to specify the value for the method attribute using a value from the System.Web.Mvc.FormMethod enumeration
BeginForm(action, controller, method, attributes) As for the previous overload, but allows you to specify attributes for the form element an object whose properties are used as the attribute names
BeginForm(action, controller, routeValues, method, attributes) As for the previous overload, but allows you to specify values for the variable route segments in your application routing configuration as an object whose properties correspond to the routing variables

Following code example demonstrate most complex version of BeginForm helper method :

This call to BeginForm produces following html :

note : You cannot specify property names in a dynamic object that contain hyphens, so I use an underscore that is then automatically mapped to a hyphen in the output, neatly side-stepping a mismatch between the C# and HTML syntaxes.

Specifying the Route Used by a Form :

If you want to ensure that a particular route is used, then you can use the BeginRouteForm helper method instead. To demonstrate this feature, I have added a new route to the /App_Start/RouteConfig.cs file.

If I call the BeginForm method with this routing configuration, I will end up with a form element whose action attribute contains a URL which is created from the default route.

You can see how I have specified that the new route should be used through the BeginRouteForm method.

This produces the following form tag, whose action attribute corresponds to the structure of the new route:

Input html helpers in MVC:

Input helpers are used to create input elements. For all of these helper methods, the first argument is used to set the value of the id and name attributes for the input element and the second argument is used to set the value attribute.

Following are basic input html helpers in ASP.NET MVC :

HTML Element Example
Check box Html.CheckBox(“myCheckbox”, false)

Output: <input id=”myCheckbox” name=”myCheckbox” type=”checkbox” value=”true” /> <input name=”myCheckbox” type=”hidden” value=”false” />

Hidden field Html.Hidden(“myHidden”, “val”)

Output: <input id=”myHidden” name=”myHidden” type=”hidden” value=”val” />

Radio button Html.RadioButton(“myRadiobutton”, “val”, true)

Output: <input checked=”checked” id=”myRadiobutton” name=”myRadiobutton” type=”radio” value=”val” />

Password Html.Password(“myPassword”, “val”)

Output: <input id=”myPassword” name=”myPassword” type=”password” value=”val” />

Text area Html.TextArea(“myTextarea”, “val”, 5, 20, null)

Output: <textarea cols=”20″ id=”myTextarea” name=”myTextarea” rows=”5″> val</textarea>

Text box Html.TextBox(“myTextbox”, “val”)

Output: <input id=”myTextbox” name=”myTextbox” type=”text” value=”val” />

Each of these helpers is overloaded. The table shows the simplest version, but you can provide an additional object argument that you use to specify HTML attributes.

Notice that the checkbox helper (Html.CheckBox) renders two input elements. It renders a checkbox and then a hidden input element of the same name.

This is because browsers do not submit a value for checkboxes when they are not selected. Having the hidden control ensures that the MVC Framework will get a value from the hidden field when this happens.

Using the Basic Input Element Helper Methods in the CreatePerson.cshtml File :

Following code shows the Input Elements Created by the Basic Input Helper Methods :

Strongly Typed Input Helpers :

For each of the basic input helpers that I described, there are corresponding strongly typed helpers.

You can see these helpers in following Table along with samples of the HTML they produce. These helpers can be used only with strongly typed views.

Html Element Example
Check box Html.CheckBoxFor(x => x.IsApproved)

Output: <input id=”IsApproved” name=”IsApproved” type=”checkbox” value=”true” /> <input name=”IsApproved” type=”hidden” value=”false” />

Hidden field Html.HiddenFor(x => x.FirstName)

Output: <input id=”FirstName” name=”FirstName” type=”hidden” value=”” />

Radio button Html.RadioButtonFor(x => x.IsApproved, “val”)

Output: <input id=”IsApproved” name=”IsApproved” type=”radio” value=”val” />

Password Html.PasswordFor(x => x.Password)

Output: <input id=”Password” name=”Password” type=”password” />

Text area Html.TextAreaFor(x => x.Bio, 5, 20, new{})

Output: <textarea cols=”20″ id=”Bio” name=”Bio” rows=”5″>Bio value</textarea>

Text box Html.TextBoxFor(x => x.FirstName)

Output: <input id=”FirstName” name=”FirstName” type=”text” value=”” />

The strongly typed input helpers work on lambda expressions. The value that is passed to the expression is the view model object, and you can select the field or property that will be used to set the value attribute.
You can see how I have used this kind of helper in the CreatePerson.cshtml view from the example application in following code :

The html generated is not different but strongly typed helpers reduce the chances of causing an error by mistyping a property name.

Select html helpers in MVC :

Helper methods that can be used to create select elements are shown in table :


Html Element Example
Drop-down list Html.DropDownList(“myList”, new SelectList(new [] {“A”, “B”}), “Choose”)

Output: <select id=”myList” name=”myList”> <option value=””>Choose</option> <option>A</option> <option>B</option> </select>

Drop-down list Html.DropDownListFor(x => x.Gender, new SelectList(new [] {“M”, “F”}))

Output: <select id=”Gender” name=”Gender”> <option>M</option> <option>F</option> </select>

Multiple-select Html.ListBox(“myList”, new MultiSelectList(new [] {“A”, “B”}))

Output: <select id=”myList” multiple=”multiple” name=”myList”> <option>A</option> <option>B</option> </select>

Multiple-select Html.ListBoxFor(x => x.Vals, new MultiSelectList(new [] {“A”, “B”}))

Output: <select id=”Vals” multiple=”multiple” name=”Vals”> <option>A</option> <option>B</option> </select>

Creating a Select Element for the Person.Role Property in the CreatePerson.cshtml File :

You can see the HTML that the latest version of the view creates, including the select element :

Summary :

  • There are 3 types of built-in html helpers :- input, select, form helpers.
  • Although using built-in helper is not mandatory, using them makes MVC app in sync with changes in routing configuration.
  • Using built-in helper makes your code clean and easy to type.


Leave a Reply

Your email address will not be published. Required fields are marked *