HTML Helpers in ASP.
NET MVC
HTML Helpers are methods in [Link] MVC that generate HTML elements dynamically in a
view. These helpers simplify the creation of form elements and other HTML controls by
providing a strongly typed and server-side way to build the HTML.
Types of HTML Helpers
Type Description Examples
Built-in methods for creating
common HTML elements like [Link](),
Standard Helpers
text boxes, buttons, dropdowns, [Link]()
etc.
Generate HTML elements tied
[Link](),
Strongly Typed Helpers to model properties, ensuring
[Link]()
type safety.
User-defined methods to create
Custom HTML helper extension
Custom Helpers reusable HTML elements
methods.
tailored to specific needs.
Description of Each Type with Code Examples
1. Standard Helpers
Description: These helpers generate HTML elements but are not tied to model
properties. They are less type-safe and require manual management of field names.
Examples:
// Controller
public ActionResult Index()
{
[Link] = "John Doe";
return View();
}
// View
@[Link]("Name", [Link], new { @class = "form-control",
placeholder = "Enter your name" })
@[Link]("Click Here", "Index", "Home", null, new { @class =
"btn btn-primary" })
2. Strongly Typed Helpers
Description: These helpers are tied to the model's properties, ensuring type safety. They
reduce runtime errors and are recommended for strongly typed views.
Examples:
// Model
public class UserModel
{
public string Name { get; set; }
}
// Controller
public ActionResult Index()
{
var model = new UserModel { Name = "John Doe" };
return View(model);
}
// View (Strongly Typed)
@model UserModel
@[Link](m => [Link], new { @class = "form-control",
placeholder = "Enter your name" })
// Model
public class UserModel
{
public string Country { get; set; }
public List<SelectListItem> Countries { get; set; }
}
// Controller
public ActionResult Index()
{
var model = new UserModel
{
Countries = new List<SelectListItem>
{
new SelectListItem { Text = "USA", Value = "USA" },
new SelectListItem { Text = "UK", Value = "UK" },
new SelectListItem { Text = "Canada", Value = "Canada" }
}
};
return View(model);
}
// View
@model UserModel
@[Link](m => [Link], [Link], "Select a
Country", new { @class = "form-select" })
3. Custom Helpers
Description: Custom HTML helpers are user-defined extension methods to create
reusable components.
Example:
// Custom Helper Class
public static class CustomHtmlHelpers
{
public static IHtmlString CustomButton(this HtmlHelper
htmlHelper, string text, string type, string cssClass)
{
return new HtmlString($"<button type='{type}'
class='{cssClass}'>{text}</button>");
}
}
// View
@[Link]("Submit", "submit", "btn btn-success")
// Model
public class UserModel
{
public string Country { get; set; }
public List<SelectListItem> Countries { get; set; }
}
// Controller
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new UserModel
{
Countries = new List<SelectListItem>
{
new SelectListItem { Text = "USA", Value = "USA" },
new SelectListItem { Text = "UK", Value = "UK" },
new SelectListItem { Text = "Canada", Value =
"Canada" }
}
};
return View(model);
}
}
// View ([Link])
@model UserModel
@[Link](m => [Link], [Link], "Select a
Country", new { @class = "form-select" })
// Custom HTML Helper Class
public static class CustomHtmlHelpers
{
public static IHtmlString CustomButton(this HtmlHelper
htmlHelper, string text, string type, string cssClass)
{
return new HtmlString($"<button type='{type}'
class='{cssClass}'>{text}</button>");
}
}
// Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
// View ([Link])
@[Link]("Click Me", "button", "btn btn-primary")
// Custom HTML Helper Class
public static class CustomHtmlHelpers
{
public static IHtmlString CustomLabel(this HtmlHelper
htmlHelper, string labelText, string cssClass)
{
return new HtmlString($"<label
class='{cssClass}'>{labelText}</label>");
}
}
// Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
// View ([Link])
@[Link]("Name:", "form-label")
Strongly Typed HTML Helpers in [Link] MVC
Strongly Typed HTML Helpers in [Link] MVC are designed to provide type safety and
IntelliSense for creating form fields and UI elements in a view. These helpers are bound to a
specific model, ensuring that field names and values correspond to properties of the model.
Benefits of Strongly Typed HTML Helpers
1. Type Safety: Validates bindings at compile-time, reducing runtime errors.
2. IntelliSense Support: Provides property suggestions while coding, improving developer
productivity.
3. Automatic Binding: Ensures seamless two-way data binding between the view and model.
Helper Description Example
Generates a text input field bound to
[Link] @[Link](m => [Link])
a model property.
Generates a multi-line text box for a @[Link](m =>
[Link]
model property. [Link])
Generates a password input field for a
[Link] @[Link](m => [Link])
model property.
Generates a checkbox for a boolean
[Link] @[Link](m => [Link])
model property.
[Link] Generates a radio button for a model @[Link](m => [Link],
r property. "Male")
[Link] Generates a dropdown list for a @[Link](m =>
For model property with a list of options. [Link], [Link])
Generates a label for a model
[Link] @[Link](m => [Link])
property.
Generates a hidden input field for a
[Link] @[Link](m => [Link])
model property.
Generates a complete input element
[Link] @[Link](m => [Link])
based on the model property type.
Renders the display value of a model
[Link] @[Link](m => [Link])
property as plain text.
Example Code: Implementing Strongly Typed HTML Helpers
1. Create the Model
namespace [Link]
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool IsActive { get; set; }
public string Gender { get; set; }
}
}
2. Create the Controller
using [Link];
using [Link];
namespace [Link]
{
public class UserController : Controller
{
public ActionResult Create()
{
return View(new User());
}
[HttpPost]
public ActionResult Create(User user)
{
if ([Link])
{
// Save the user to the database (example purpose)
return RedirectToAction("Details", new { id =
[Link] });
}
return View(user);
}
}
}
4. Create the Strongly Typed View
@model [Link]
<!DOCTYPE html>
<html>
<head>
<title>Create User</title>
</head>
<body>
<h1>Create User</h1>
@using ([Link]())
{
<div>
@[Link](m => [Link])
@[Link](m => [Link])
</div>
<div>
@[Link](m => [Link])
@[Link](m => [Link])
</div>
<div>
@[Link](m => [Link])
@[Link](m => [Link])
</div>
<div>
@[Link](m => [Link])
@[Link](m => [Link])
</div>
<div>
<label>Gender</label>
@[Link](m => [Link], "Male") Male
@[Link](m => [Link], "Female") Female
</div>
<button type="submit">Submit</button>
}
</body>
</html>
Implementation of Strongly Typed HTML Helpers
namespace [Link]
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool IsActive { get; set; }
public string Gender { get; set; }
public string Country { get; set; }
}
}
using [Link];
using [Link];
namespace [Link]
{
public class UserController : Controller
{
public ActionResult Create()
{
return View(new User());
}
[HttpPost]
public ActionResult Create(User user)
{
if ([Link])
{
// Logic to save the user (e.g., database)
return RedirectToAction("Details", new { id =
[Link] });
}
return View(user);
}
}
}
@model [Link]
<!DOCTYPE html>
<html>
<head>
<title>Create User</title>
</head>
<body>
<h1>Create User</h1>
@using ([Link]())
{
<div>
@[Link](m => [Link])
@[Link](m => [Link])
</div>
<div>
@[Link](m => [Link])
@[Link](m => [Link])
</div>
<div>
@[Link](m => [Link])
@[Link](m => [Link])
</div>
<div>
@[Link](m => [Link])
@[Link](m => [Link])
</div>
<div>
<label>Gender</label>
@[Link](m => [Link], "Male") Male
@[Link](m => [Link], "Female") Female
</div>
<div>
@[Link](m => [Link])
@[Link](m => [Link], new
SelectList(new[] { "USA", "UK", "Canada" }))
</div>
<button type="submit">Submit</button>
}
</body>
</html>
HTML Helper Method Description Example Code
Generates a hyperlink (<a> tag) @[Link]("Home", "Index",
[Link]() that links to a specified action "Home", null, new { @class = "btn
method. btn-link" })
Creates an HTML <form> @using ([Link]("Submit",
[Link]() element that posts data to the "Home", [Link])) { /*
server. form fields */ }
Generates an HTML <input> @[Link]("Name", "John Doe",
[Link]() new { @class = "form-control" })
element of type "text".
Generates an HTML <input> @[Link](m => [Link],
[Link]() element of type "text" for a model new { @class = "form-control",
property. placeholder = "Enter name" })
Creates an HTML <input> @[Link]("Password", null,
[Link]() new { @class = "form-control" })
element of type "password".
Creates an HTML <input> @[Link](m =>
[Link]() element of type "password" for a [Link], new { @class = "form-
model property. control" })
@[Link]("Description",
Generates an HTML <textarea>
[Link]() "Default text", new { @class =
element for multiline input. "form-control" })
@[Link](m =>
Generates an HTML <textarea>
[Link]() [Link], new { @class =
element for a model property. "form-control" })
Creates an HTML <input>
[Link]() @[Link]("IsActive", true)
element of type "checkbox".
Creates an HTML <input>
@[Link](m =>
[Link]() element of type "checkbox" for a [Link])
model property.
Creates an HTML <input> @[Link]("Gender",
[Link]() "Male", true)
element of type "radio".
Creates an HTML <input>
@[Link](m =>
[Link]() element of type "radio" for a [Link], "Male")
model property.
@[Link]("Country",
Generates a <select> element
[Link]() new SelectList([Link]),
with a list of options. "Select a Country")
Generates a <select> element @[Link](m =>
[Link], new
[Link]() for a model property with a list of SelectList([Link]), "Select
options. a Country")
Creates an HTML <select>
@[Link]("Options", new
[Link]() element that allows multiple MultiSelectList([Link]))
selections.
Creates a <select> element for a @[Link](m =>
[Link]() model property, allowing multiple [Link], new
selections. MultiSelectList([Link]))
Generates a hidden <input>
[Link]() @[Link]("Id", 123)
element for passing data.
Generates a hidden <input>
[Link]() @[Link](m => [Link])
element for a model property.
Displays a validation message for @[Link]("Name",
[Link]() "Name is required.")
a specific field.
Displays a validation message for @[Link](m =>
[Link]() [Link])
a model property.
Renders a partial view inside the
[Link]() @[Link]("_PartialViewName")
main view.
Renders a partial view directly @{ [Link]("_PartialView
[Link]() Name"); }
into the response stream.
Creates an appropriate input
[Link]() element based on the model’s @[Link]("Name")
data type.
Creates an appropriate input
[Link]() element for a model property @[Link](m => [Link])
based on its data type.
Displays the value of a model
[Link]() @[Link]("Name")
property in a read-only manner.
[Link]() Displays the value of a model @[Link](m => [Link])
property in a strongly typed
manner.
Generates an HTML <label>
[Link]() @[Link]("Name", "Full Name")
element for a field.
Generates an HTML <label>
[Link]() @[Link](m => [Link])
element for a model property.