Introduction
In ASP.NET MVC, HTML Helpers are methods used in Razor Views to generate HTML elements easily.
Instead of writing large HTML code manually, HTML Helpers allow developers to generate HTML elements using C# code.
They help to:
Reduce repetitive code
Bind data with models
Improve readability
Generate strongly typed UI elements
Example Razor View file:
Views/Home/Index.cshtml
Types of HTML Helpers
In MVC there are 3 main types of HTML Helpers.
| Type | Description |
|---|---|
| Standard HTML Helpers | Generate simple HTML elements |
| Strongly Typed HTML Helpers | Bind elements with Model properties |
| Templated HTML Helpers | Automatically generate UI for model |
1 Standard HTML Helpers
These helpers generate basic HTML elements.
Example: TextBox
@Html.TextBox("username")
Generated HTML:
<input type="text" name="username" />
What is this?
When to Use
Use when no model binding is required.
Example: simple login forms.
Common Standard HTML Helpers
1 TextBox
Creates a text input.
@Html.TextBox("Name")
Output
<input type="text" name="Name" />
What is this?
2 Password
Used for password fields.
@Html.Password("Password")
Output
<input type="password" name="Password" />
What is this?
3 TextArea
Used for multi-line text input.
@Html.TextArea("Address")
Output
<textarea name="Address"></textarea>
What is this?
4 CheckBox
Used for boolean values.
@Html.CheckBox("IsActive")
Output
<input type="checkbox" name="IsActive" />
What is this?
5 RadioButton
Used for selecting one option.
@Html.RadioButton("Gender", "Male") Male
@Html.RadioButton("Gender", "Female") Female
6 DropDownList
Used to create dropdown lists.
@Html.DropDownList("City", new List<SelectListItem>
{
new SelectListItem{ Text="Ahmedabad", Value="1"},
new SelectListItem{ Text="Surat", Value="2"}
})
Output
<select name="City">
<option value="1">Ahmedabad</option>
<option value="2">Surat</option>
</select>
What is this?
7 ListBox
Used for multiple selections.
@Html.ListBox("Skills", new MultiSelectList(ViewBag.Skills))
8 Hidden Field
Stores hidden values.
@Html.Hidden("UserId", 10)
Output
Join the conversation! Your thoughts help the community grow.