Before looking into how to use the HTML helper methods in MVC Views let’s first understand what are the problems that HTML helpers solves.
HTML helpers have a very specific use which is to generate the HTML for the containing view. In any web page we need a form element which may contain some child HTML elements like the input fields to enable the user to provide input values and interact with our application.
Though we can write the html elements ourselves,after all html elements consists of simple opening and closing tags, but the HTML helpers generates html tags for us and we don’t have to write all the boilerplate code. If we take the example of the form tag ,it is written as
<form action="”url”" method="”get”"> </form>
The action attribute points to the url to which our web page will be submitted while the method attribute can be Get or Post.
If we write the above HTML then we need to verify if our url is correctly refering to the action method in the controller which complies with the routes defined by our application
We can generate the similar html using the BeginForm() html helper.But if we use the BeginForm() html helper method then the generated form tag will use the correct routing configuration for the action method.Also if the routing configuration changes in our application BeginForm() will take care of it.
So following are the benefits of HTML helpers over writing the html elements ourselves.
- We don’t have to worry about forgetting the closing tag or any any other markup as the html is generated by another well tested component the “HTMLHelper method” which ensures that only valid html is generated.
- Writing html elements by hand in a large enterprise application can get tedious. We don’t need to write boilerplate code again and again.
- HTML helpers provides few features by default like encoding attribute values to prevent cross site scripting attacks ,generated url’s points to the correct server resources and binding the html elements to the model object so the model changes are reflected in the html elements.
HTML helpers are implemented as methods which generate chunk of HTML.Helper methods can be accessed in a view using the HTML property.Every view has an implicit base class.In the case of razor views it is WebViewPage and for the WebForms views it is ViewPage which defines the HTML property for which all the extension methods are defined ,so the helper methods are accessible via the HTML property in all the views which we create.
There are two versions of the HTML helper methods the normal html helper methods and strongly typed.The difference is that the normal HTML helpers are unaware of the model for the view while the strongly typed version knows about the model.
As the strongly typed version is aware of the model so any changes in the model such as changing the name of the property or removing a property are recognized.So an advantage of using the strongly typed helper methods is that errors such as typing wrong property name are caught at compile time instead of runtime.
Another advantage of the strongly typed methods is that we get the visual studio intellisense support which is not available for the normal helper methods.
We will see common HTML helpers along with the strongly typed versions and the html elements that they generate.
@Html.BeginForm The BeginForm helper method generates the form element.It posts to a controller action method which we can specify as the method parameters.The following BeginForm() method will post to the EmployeeDetails method of the Home Controller.
@using (Html.BeginForm("EmployeeDetails", "Home")) { }
If we don’t specify a value for the action method and controller parameters then by default the BeginForm() method posts to the same action method and controller which returned the view.
Html helpers for form elements have a normal strongly typed version.Unlike normal html helper methods in which we pass a string literal ,we pass a model object as lambda expression parameter to the strongly typed methods.
@Html.TextBox We can use the TextBox helper method to generate input field for the user.It renders the input html tag with the type attribute set to “text”.
It has different overloads which we can use to specify different properties like html attributes and the format.We can use the following overload to specify the name ,value and the html attributes for the textbox.
@Html.TextBox(String nameOfTextBox, Object value, Object htmlAttributes)
If we call the method with the below argument values
@Html.TextBox("name", "john", new { id = "nameId" })
we get the following html rendered by the helper .Since we have explicitly set the value of the id attribute in the helper above it is rendered in the input tag.If we don’t explicitly set the value of id then the id value will be same as the name.
<input id="nameId" name="name" type="text" value="john" />
Strongly typed version of the TextBox helper is TextBoxFor().So to render a textbox for name property we use the TextBoxFor() helper as
@Html.TextBoxFor(model => model.name)
As with other strongly typed helper methods it expects a lambda expression.
@Html.DropdownList and @Html.Listbox These are used to generate the list with multiple values from which user can select single or multiple values,dropdownlist allows single selection while listbox helper selects multiple selection.Both of these helpers are rendered as a select element.The difference between the two is that dropdownlist helper method renders a dropdown list in which only a single item can be selected while listbox helper renders a list which allows to select multiple items at a time.
We can use the DropDownList method to render a list containing three items in which the item with value 3 is selected as
@Html.DropDownList("courses", new SelectList( new List<Object>{ new { Text = "Computers", Value = 1 }, new { Text = "Electronics", Value = 2 }, new { Text = "Mechanical", Value = 3} }, "Value", "Text", 3))
We get the following dropdown on executing the view containing the above code.Mechanical list item is selected as we have given the select index as 3 above.
If we want to create a listbox instead of dropdownlist we can use the listbox helper method as
@Html.ListBox("courses", new SelectList( new List<Object>{ new { Text = "Computers", Value = 1 }, new { Text = "Electronics", Value = 2 }, new { Text = "Mechanical", Value = 3} }, "Value", "Text", 3))
The following listbox is rendered by the above listbox helper method.
@Html.Password This renders an input password field ,in which user typed value is masked so that it is not visible on screen. To generate a password field having id password we can use the following helper method
@Html.Password(“password”)
in the generated input field entered values are not visible on screen
The above Password helper renders the following input element
<input id=”password” name=”password” type=”password” />
@Html.Hidden This renders a hidden field with id and value being set with the method arguments.If we have a id field in our model then we can use the following to set the field with its value.
@Html.Hidden(“id”)
The following input element will be generated by using the above helper method.The value is set as 1 below as it is the value of the id field in the model.
<input id="id" name="id" type="hidden" value="1" />
We can use the strongly typed method also to set the hidden field with the id value as
@Html.HiddenFor(model=>model.id)
If we want to set the hidden field with some other value then we can pass the value explicitly as
@Html.Hidden("id","11")
@Html.RadioButton HTML Radiobutton displays a list of choices from which user can select a single value.Radiobuttons are usually placed in a group with each each radio button having the same name.We can use the RadioButton helper to generate the html radio buttons.
Below we are creating radio buttons for three products from which user can select a single product.We have passing the same name to the three helper methods so that the rendered radio buttons will belong to the same group.To the second method we are passing the value true for the third argument as we want the tv radio button selected by default.
<span>computer</span> @Html.RadioButton("product", "computer") <span>tv</span> @Html.RadioButton("product", "tv", true) <span>mp3</span> @Html.RadioButton("product", "mp3")
The above methods displays a group of radio buttons.
Following html is rendered by the above methods
<input id="product" name="product" type="radio" value="computer" /> <input checked="checked" id="product" name="product" type="radio" value="tv" /> <input id="color" name="product" type="radio" value="mp3" />
We can bind the htmlhelper method to a model property using the strongly typed version.So if we have a model property called product
@Html.RadioButtonFor(model => model.product, "1") @Html.RadioButtonFor(model => model.product, "2") @Html.RadioButtonFor(model => model.product, "3")
@Html.CheckBox This renders a checkbox which user can select or deselect.It acts as a true/false field. To render a checkbox with name print we can use it as
@Html.CheckBox("print")
If we want to make the rendered checkbox selected by default then we can pass the value true to the second argument.
@Html.CheckBox("print",true)
The strongly typed version binds to a boolean model property.If we have a boolean model property print then we can call the method as
@Html.CheckBoxFor(model=>model.print)
@Html.ActionLink We can create an HTML link using this helper method.This is one of the most useful methods since it takes care of the routing information .Routes are not only responsible for matching the incoming urls but also helps generate outgoing urls,which are urls which are generated as a part of our view rendering.
For example if we want to render a hyperlink which posts to the Details action of the Home controller then we will use the following
@Html.ActionLink("Employee Details","Details","Home")
The first parameter above is the link text, and the second parameter is the name of the controller action.
It renders the following HTML:
<a href="/Home/About">About this Website</a>
The above link is generated by checking the routing information defined by our application.So we should use the ActionLink() helper for generating the outgoing urls instead of hardcoding the urls in our views.
@Html.ValidationSummary This is used to show the errors to the user.It renders a list which contains the errors which are contained in the ModelState dictionary.
In the action method we can add the errors in the ModelState dictionary.We can add the errors as model errors or as property errors.
ModelState.AddModelError("", "This is a Model error"); //model error ModelState.AddModelError("propertyerror", "This is a Property error"); //property error
To display the errors we can use the helper method as
@Html.ValidationSummary(false)//displays model errors @Html.ValidationSummary(true)//displays property errors
So as we have seen above Html helper methods in MVC renders html markup.They also help avoid code redundancy and provide few features like encoding out of the box.
If we need some functionality which is not covered by the the inbuilt helpers we can create our own helper methods.
Leave a Reply