HTML Helpers in MVC: Part 1

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

  1. Rendering TextBox using HTML elements 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 drop-down list control
  8. Strongly-typed HTML helpers
  9. Default selection in a drop-down list control

HTML Helper

An 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.

Input type

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

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

@Html.

TextBox control

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 “my name” here.

TextBox HTML

@Html.TextBox("myname")

Run the application.

Run application

In the output we got two TextBox controls, one is rendered using an HTML element and another is rendered using an 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.

Page source

Look at the ID and name attributes of both of the generated controls.

Generated controls

When we create a TextBox using an HTML element, we specify the name and id attribute but when we create a TextBox using an 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.

Default value

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.

Overload version

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

Second overloaded version

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

Run the application.

Default value two

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.

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

Background color

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 the htmlAttribute of the type object.

 HTML element

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.

Style attribute

Run the application.

Parameter

Go to the page source.

Style background

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.

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

Placeholder

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

Displayed value

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

Reserved keywords

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.

CSS class

Run the application.

Stylesheet file

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").

HTML helper

Run the application.

HTML element

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.

Multi-line TextBox

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.

Fifth parameter

Generating a dropdown list control

To generate a TextBox, we use the @Html.Textbox() HTML helper and to generate a drop-down list we use the @Html.Dropdownlist() HTML helper.

In MVC, a drop-down list 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 dropdown list.

To create a drop-down list using HTML helper, we say.

@Html.DropDownList(

Drop-down list

There are eight overloaded versions of this method. To provide your dropdown list 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.

SelectListItem

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.

IEnumerable

Now based on your requirements if you want to add a text, or value, 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.

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

So, we have successfully added two SelectListItems to our drop-down list.

Run the application.

Two SelectListItems

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.

Select City

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

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

Run the application.

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

 Select City label

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

City names

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 dropdown list from a database table.

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

Entity Framework

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.

NuGet Package Manager

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

Online packages

Select the project.

Select the project

Click I accept.

Accept

Wait until it is installed.

Installed.

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

Green mark sign

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.

Class file one

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.

DataAnnotations

Class file two

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

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.

DbSet

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.

<connectionStrings>
    <add name="CityDB" connectionString="server=.;database=db_sample;user=sa;password=sql" providerName="System.Data.SqlClient"/>
</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 are present in HtmlHelpersInMVC.Controllers. So, before creating the instance of this class, we must import the namespace.

HomeController's

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, and 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.

ViewBag

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.

Optional string label.

Save and run the application.

Save and run

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.

CityList

In the CityList class, we have added the property “Cities” which 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.

IndexTwo action

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 the class as CityList.

Empty template

Click Add.

When the 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.

IndexTwo

The next step is to create a dropdown list using the DropDownListFor HTML helper.

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

Run the application.

Kolkata

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.

Compile-time error

Example 4

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

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.

SelectList constructor

Specify the value of New Delhi which is 102.

New Delhi

Run the application.

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
    TblCity set 

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

Nullable Boolean

Build the project.

In the HomeController's Index action write the following.

Index action

  • In the Index action method, we created a new object of the CityDb class that will help this application interact with the database.
  • As we know drop-down list 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 retrieved the value from the IsSelected property and assigned 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.

New Delhi

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

UPDATE tblCity
SET IsSelected = 1
WHERE Id = 104;

Run the application.

Index

I hope you like it. Thank you.


Similar Articles