HTML Helpers in MVC: Part 1

The following are the topics we will discuss in this article:

  1. Rendering TextBox using HTML element and HTML Helpers
  2. Adding styles to the TextBox control
  3. Rendering a Label control
  4. Rendering a Hidden Field control
  5. Rendering a TextArea control
  6. Rendering a Dropdownlist control
  7. How to bind records from the database to a dropdownlist control
  8. Strongly-typed HTML helpers
  9. Default selection in a dropdownlist control
HTML Helper

A HTML helper is a special type of method used to render HTML content in a view.

Let's look at some of the examples.

Example 1

Let's see which standard HTML element can be used to render a TextBox control.

We can use the <input type=”text”> to render a text box control.



In the preceding input type, we have created a TextBox control with an id “myname” and name “myname”.

We can create the same TextBox control using a HTML helper and to create a TextBox using a HTML helper we say:

@Html.



Look at the intellisense, this Html property gets or sets the HtmlHelper object that is used to render HTML elements.

@Html.TextBox(

Look at the type of parameter. This TextBox HTML helper is expecting “string”. So, we can pass “myname” here.


@Html.TextBox("myname")

Run the application.


In the output we got two TextBox controls, one is rendered using a HTML element and another is rendered using a HTML helper.

Go to the page source of this page and to do that right-click anywhere on the web page and select view source.



Look at the id and name attribute of both of the generated controls.



When we create a TextBox using a HTML element, we specify the name and id attribute but when we create a TextBox using a HTML helper all we need to do is specify a name and when this TextBox is rendered it uses this name value and assigns this value to the name attribute and id attribute.

@Html.TextBox("myname")

Let's say we want a default value to be displayed in the TextBox control, whenever we navigate to this page.

Using HTML element

We need to specify the default value in the value attribute.



Using HTML helper

If you look at this TextBox html helper method, there are seven overloaded versions to choose from.

To specify the id and name attribute we use the first overload version.



To specify the value, we can use the second overloaded version that expects a parameter of type object value.



@Html.TextBox("myname","Default Value Two")

Run the application.


Now let's say we want to change the background color of both of the TextBoxes to Red.

Using HTML element

To change the background color we can use the style attribute.

  1. <input type="text" name="myname" id="myname" value="Default value" style="background-color:red" />  


Now let's see how to do the same thing in the HTML helper TextBox method.

Using HTML helper

Style is an attribute of an HTML element right for setting the background-color property to Red.

In the TextBox HTML helper, there is another overloaded version that expects htmlAttribute of type object.



Look at the parameter above, it says htmlAttribute and style is nothing but an HTML attribute.

So, in this parameter we can create a new style attribute.



Run the application.


Go to the page source.



In the preceding you can see the anonymous type (style) we created is rendered into an attribute of the HTML element.

NOTE

new{} is used to create an anonymous type and in this we can set “n” number of attributes, each separated by a comma.

Let's say we don't want a default value for the TextBox HTML helper anymore and we want to replace this with a placeholder. So, all we need to do is create another anonymous type and separate it with a comma.

  1. @Html.TextBox("myname"nullnew {style="background-color:red", placeholder="Please enter name" })  


Go to the page source, you will see an attribute “placeholder” with the preceding displayed value.



Some of the HTML attributes like class, read-only are reserved keywords. If we try to use the class attribute, we will get a compiler error.



So, how is it possible to use this “class” attribute?

To use this attribute, use an “@” symbol as in @class= className.

Since we have specified a CSS class name, let's create an internal stylesheet file.



Run the application.


If you want to make this TextBox read-only, use @readonly = “true”.

Example 2

To generate a label we use a <Label></Label> HTML element.

<label>Html Element Name</label>

To generate the same label using HTML helper, we use @Html.Label("Html Helper Name").



Run the application.



To create a label we used the @Html.Label() HTML helper and just like that if you want to create an input type “password” we can use @Html.Pasword().

To create a hidden field we can use @Html.Hidden(). A hidden field is used to store id values. By default Id values are not displayed on the page to the end user but when the page is posted back, we need this Id value to update the user data.

If you want to generate a multi-line TextBox with 3 rows and 2 columns then use the seventh overloaded version of the TextArea HTML helper.



The first parameter expects a name for this control.

The second parameter expects a default value to be displayed.

The third parameter is the row value.

The fourth parameter is the column value.

The fifth parameter is the object htmlAttribute that we already discussed, if you don't want to create an anonymous type then just pass null.

@Html.TextArea("comment","",3,2,null)

Run the application.



Generating a dropdown list control

To generate a TextBox, we use the @Html.Textbox() HTML helper and to generate a dropdownlist we use the @Html.Dropdownlist() HTML helper.

In MVC, a dropdownlist is a collection of SelectListItem objects. Based on your requirements you can either hard-code the values or retrieve them from a database table.

Let's look at an example.

Example 1

In this example we will see how to hardcode the values for the dropdownlist.

To create a dropdownlist using HTML helper, we say:

@Html.DropDownList(


There are eight overloaded versions of this method. To provide your dropdownlist control a name, use the first overloaded version.

@Html.DropDownList(“City”)

As we know a dropdownlist in MVC is a collection of SelectListItem objects and to add these objects we need to use the other overloaded version of this dropdownlist HTML helper.


The parameter type that we can pass should be of type IEnumerable. So, we can say:

new List<SelectListItem>() { new SelectListItem { } } because this List class implements the IEnumerable interface.



Now based on your requirements if you want to add a text, value, or provide this a group name, or want to keep an item selected by default, we can do these all by using the properties shown above.

  1. @Html.DropDownList("City"new List<SelectListItem>() {  
  2. new SelectListItem { Text = "Kolkata", Value = "Kolkata" },  
  3. new SelectListItem { Text = "New Delhi", Value = "New Delhi" }  
  4. })  

So, we have successfully added two SelectListItems to our dropdownlist.

Run the application.


We got the expected output.

But let's say we don't want a city name to be displayed first, we want to add an optional label “Select City” at the beginning and for that we can use the fifth overloaded version of this method.



Pass “Select City” as a value in this parameter.

  1. @Html.DropDownList("City"new List<SelectListItem>() {  
  2. new SelectListItem { Text = "Kolkata", Value = "Kolkata" },  
  3. new SelectListItem { Text = "New Delhi", Value = "New Delhi" } },  
  4. "Select City")  
Run the application.

You will see the Select City label will be displayed first.


Click the dropdown icon, the city names will be displayed.



Dis-advantage of hardcoding the values

In case there is a requirement to add more cities, then for that we need to create a new SelectListItem object again which will take time and it would be difficult to manage the code.

Example 2

In this example, we will see how to bind values to the dropdownlist from a database table.

For the demo we will be using Entity Framework to retrieve the data from this table.



Step 1

The first step is to install the Entity Framework and for that go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution.



Expand the Online packages then select nugget.org then select Entity Framework then click Install.



Select the project.



Click I accept.



Wait until it is installed.



Once the installation is complete, you will see the Green mark sign at the top-right corner of EntityFramework. Click Close.



Step 2

The next step is to add two class files to the Models folder.

Class file one

Give this class file the name “City.cs” and add two auto-implemented properties.



Since we are retrieving the records from an existing database table we need to map our class with the database table and for that we can use the table attribute in the System.ComponentModel.DataAnnotations.Schema namespace.



Class file two

Give this class file the name “CityDB.cs” and inherit this class from DbContext.



NOTE

DbContext and DbSet are present in the System.Data.Entity namespace.

Now in this class add a property of type DbSet<City> as in the following:



To learn more about DbContext and DbSet click here.

After adding these two class files build the solution.

Step 3

Add a connection string to the root web.config file with the same name as that of the CityDB class.

  1. <connectionStrings>  
  2. <add name="CityDB" connectionString="server=.;database=db_sample;user=sa;password=sql" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  
Step 4

Create an instance of the CityDB class in the HomeController's Index method.

NOTE: This CityDB class is present in HtmlHelpersInMVC.Models and HomeController is present in HtmlHelpersInMVC.Controllers. So, before creating the instance of this class, we must import the namespace.



In the Index action method we have created an instance of the CityDB class.

As we know this CityDb.Cities is a collection of list items. So, pass this item in the first parameter of the SelectList constructor, pass the Id as the DataValueField and CityName as the DataTextField.

We are assigning it to the ViewBag dynamic property and returning the view.

To learn more about ViewBag click here.


Step 5

In our Index view, we need to make some changes.

In the first parameter of the Dropdownlist HTML helper method pass the ViewBag's dynamic property that is Cities and in the second parameter pass the optional string label.


Save and run the application.



Example 3

Along with the DropDownList HTML helper there is another HTML helper DropDownListFor. This DropDownListFor HTML helper can be used when we create strongly typed views.

In the models folder create another class file “CityList” and add the following to it.


In the CityList class we have added the property “Cities” that returns a list of cities back. In the get accessor of this property we created a new object of CityDB and returned the Cities back.

Flip to HomeController and create an instance of this CityList class in the IndexTwo action method.


The next step is to add a view and for that right-click on the IndexTwo method and click Add view.

Select an empty template and model class as CityList.



Click Add.

When IndexTwo.cshtml file is generated you will see at the top the model @model HtmlHelpersInMVC.Models.CityList that means it is a strongly-typed view.



The next step is to create a dropdownlist using DropDownListFor HTML helper.

  1. <div>  
  2. @Html.DropDownListFor(x => x.Cities, new SelectList(Model.Cities, "Id", "CityName"),"Select City")  
  3. </div>  

Run the application.


NOTE

In strongly-typed views the name is inferred using a lambda expression.

Advantage of using a strongly-typed view

This strongly typed HTML helper provides a compile-time error check, meaning that if we change the property name from Cities to Citie we will get an error.



Example 4

The following are the options that where loaded from the database table.


But when we run the application, notice that no City is selected as a default and let's say our requirement is such that we want New Delhi to be selected by default.

To do that we can use another overloaded version of this SelectList constructor.



Specify the value of New Delhi which is 102.



Run the application.



We get the output as expected but let's say for some reason we want Jamshedpur to be displayed as the default selection and for that we need to modify the application code. So if the change is frequent then it would be better to make a default selection using a database table.

In our current table tblCity we will add another column IsSelected of type bit. So, either 1 or 0 or null.

Write the following query in SQL Server and execute it.

  1. alter table tblCity add IsSelected BIT  
  2. Update tblCity set IsSelected = 1 where Id = 102  



In the City class file add a nullable Boolean property IsSelected.



Build the project.

In the HomeController's Index action write the following:


  • In the Index action method, we created a new object of CityDb class that will help this application to interact with the database.
  • As we know dropdownlist is a collection of SelectListItem objects, so we have created an object of type List<SelectListItem>.
  • In the CityDb.cs we have created a property of type DbSet<City> that will provide us all the rows from tblCity and for that we need to invoke the Cities property and since this Cities property will provide a City object back we are looping through each City present in the Cities property.
  • Inside the loop, we created a new SelectListItem object and in this object there are a few properties of the SelectListItem class that will be handy, like Text, Value and Selected.
  • In the Text property we passed the CityName. In the value property we passed the Id and in the Selected property we passed cities.IsSelected.HasValue ? cities.IsSelected.Value : false

Which is nothing but a condition and to pass this condition we used a ternary operator. Here we checked if the IsSelected has any value and to do that we used the HasValue property, if yes(?) then we are retrieving the value from the IsSelected property and assigning it to the Selected property so it will pass 1 to this property that is nothing but a true and if there is no value(:) then we are passing false.

  • After each loop we are adding the SelectListItem to the List object SelectList that we created.
  • Finally we passed the same SelectList list object to the ViewBag and returned a view.

Save and run the application

In the output you will see New Delhi is selected as the default option.



Now let's say we want Jamshedpur to be selected as the default option, for that first we need to update the IsSelected column in the database table.

  1. Update tblCity set IsSelected = 1 where Id = 104;  
Run the application.



I hope you like it. Thank you.