0% found this document useful (0 votes)
34 views

HTML Helpers

NOne

Uploaded by

ali.fatmi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

HTML Helpers

NOne

Uploaded by

ali.fatmi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

HTML Helpers in ASP.

NET MVC

HTML Helpers are methods in ASP.NET 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 Html.TextBox(),
Standard Helpers
text boxes, buttons, dropdowns, Html.ActionLink()
etc.
Generate HTML elements tied
Html.TextBoxFor(),
Strongly Typed Helpers to model properties, ensuring
Html.DropDownListFor()
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()
{
ViewBag.Name = "John Doe";
return View();
}

// View
@Html.TextBox("Name", ViewBag.Name, new { @class = "form-control",
placeholder = "Enter your name" })

@Html.ActionLink("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
@Html.TextBoxFor(m => m.Name, 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
@Html.DropDownListFor(m => m.Country, Model.Countries, "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
@Html.CustomButton("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 (Index.cshtml)
@model UserModel
@Html.DropDownListFor(m => m.Country, Model.Countries, "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 (Index.cshtml)
@Html.CustomButton("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 (Index.cshtml)
@Html.CustomLabel("Name:", "form-label")
Strongly Typed HTML Helpers in ASP.NET MVC

Strongly Typed HTML Helpers in ASP.NET 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
Html.TextBoxFor @Html.TextBoxFor(m => m.Name)
a model property.
Generates a multi-line text box for a @Html.TextAreaFor(m =>
Html.TextAreaFor
model property. m.Description)
Generates a password input field for a
Html.PasswordFor @Html.PasswordFor(m => m.Password)
model property.
Generates a checkbox for a boolean
Html.CheckBoxFor @Html.CheckBoxFor(m => m.IsActive)
model property.
Html.RadioButtonFo Generates a radio button for a model @Html.RadioButtonFor(m => m.Gender,
r property. "Male")
Html.DropDownList Generates a dropdown list for a @Html.DropDownListFor(m =>
For model property with a list of options. m.Country, Model.Countries)
Generates a label for a model
Html.LabelFor @Html.LabelFor(m => m.Name)
property.
Generates a hidden input field for a
Html.HiddenFor @Html.HiddenFor(m => m.Id)
model property.
Generates a complete input element
Html.EditorFor @Html.EditorFor(m => m.Name)
based on the model property type.
Renders the display value of a model
Html.DisplayFor @Html.DisplayFor(m => m.Email)
property as plain text.

Example Code: Implementing Strongly Typed HTML Helpers

1. Create the Model

namespace YourNamespace.Models
{
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 System.Web.Mvc;
using YourNamespace.Models;

namespace YourNamespace.Controllers
{
public class UserController : Controller
{
public ActionResult Create()
{
return View(new User());
}

[HttpPost]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
// Save the user to the database (example purpose)
return RedirectToAction("Details", new { id =
user.Id });
}
return View(user);
}
}
}

4. Create the Strongly Typed View

@model YourNamespace.Models.User

<!DOCTYPE html>
<html>
<head>
<title>Create User</title>
</head>
<body>
<h1>Create User</h1>
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
</div>

<div>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
</div>

<div>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</div>

<div>
@Html.LabelFor(m => m.IsActive)
@Html.CheckBoxFor(m => m.IsActive)
</div>

<div>
<label>Gender</label>
@Html.RadioButtonFor(m => m.Gender, "Male") Male
@Html.RadioButtonFor(m => m.Gender, "Female") Female
</div>

<button type="submit">Submit</button>
}
</body>
</html>

Implementation of Strongly Typed HTML Helpers

namespace YourNamespace.Models
{
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 System.Web.Mvc;
using YourNamespace.Models;

namespace YourNamespace.Controllers
{
public class UserController : Controller
{
public ActionResult Create()
{
return View(new User());
}

[HttpPost]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
// Logic to save the user (e.g., database)
return RedirectToAction("Details", new { id =
user.Id });
}
return View(user);
}
}
}

@model YourNamespace.Models.User

<!DOCTYPE html>
<html>
<head>
<title>Create User</title>
</head>
<body>
<h1>Create User</h1>

@using (Html.BeginForm())
{
<div>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
</div>

<div>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
</div>

<div>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</div>

<div>
@Html.LabelFor(m => m.IsActive)
@Html.CheckBoxFor(m => m.IsActive)
</div>

<div>
<label>Gender</label>
@Html.RadioButtonFor(m => m.Gender, "Male") Male
@Html.RadioButtonFor(m => m.Gender, "Female") Female
</div>

<div>
@Html.LabelFor(m => m.Country)
@Html.DropDownListFor(m => m.Country, 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) @Html.ActionLink("Home", "Index",
Html.ActionLink() that links to a specified action "Home", null, new { @class = "btn
method. btn-link" })
Creates an HTML <form> @using (Html.BeginForm("Submit",
Html.BeginForm() element that posts data to the "Home", FormMethod.Post)) { /*
server. form fields */ }
Generates an HTML <input> @Html.TextBox("Name", "John Doe",
Html.TextBox() new { @class = "form-control" })
element of type "text".
Generates an HTML <input> @Html.TextBoxFor(m => m.Name,
Html.TextBoxFor() element of type "text" for a model new { @class = "form-control",
property. placeholder = "Enter name" })
Creates an HTML <input> @Html.Password("Password", null,
Html.Password() new { @class = "form-control" })
element of type "password".
Creates an HTML <input> @Html.PasswordFor(m =>
Html.PasswordFor() element of type "password" for a m.Password, new { @class = "form-
model property. control" })
@Html.TextArea("Description",
Generates an HTML <textarea>
Html.TextArea() "Default text", new { @class =
element for multiline input. "form-control" })
@Html.TextAreaFor(m =>
Generates an HTML <textarea>
Html.TextAreaFor() m.Description, new { @class =
element for a model property. "form-control" })
Creates an HTML <input>
Html.CheckBox() @Html.CheckBox("IsActive", true)
element of type "checkbox".
Creates an HTML <input>
@Html.CheckBoxFor(m =>
Html.CheckBoxFor() element of type "checkbox" for a m.IsActive)
model property.
Creates an HTML <input> @Html.RadioButton("Gender",
Html.RadioButton() "Male", true)
element of type "radio".
Creates an HTML <input>
@Html.RadioButtonFor(m =>
Html.RadioButtonFor() element of type "radio" for a m.Gender, "Male")
model property.
@Html.DropDownList("Country",
Generates a <select> element
Html.DropDownList() new SelectList(Model.Countries),
with a list of options. "Select a Country")
Generates a <select> element @Html.DropDownListFor(m =>
m.Country, new
Html.DropDownListFor() for a model property with a list of SelectList(Model.Countries), "Select
options. a Country")
Creates an HTML <select>
@Html.ListBox("Options", new
Html.ListBox() element that allows multiple MultiSelectList(Model.Options))
selections.
Creates a <select> element for a @Html.ListBoxFor(m =>
Html.ListBoxFor() model property, allowing multiple m.SelectedOptions, new
selections. MultiSelectList(Model.Options))
Generates a hidden <input>
Html.Hidden() @Html.Hidden("Id", 123)
element for passing data.
Generates a hidden <input>
Html.HiddenFor() @Html.HiddenFor(m => m.Id)
element for a model property.
Displays a validation message for @Html.ValidationMessage("Name",
Html.ValidationMessage() "Name is required.")
a specific field.
Displays a validation message for @Html.ValidationMessageFor(m =>
Html.ValidationMessageFor() m.Name)
a model property.
Renders a partial view inside the
Html.Partial() @Html.Partial("_PartialViewName")
main view.
Renders a partial view directly @{ Html.RenderPartial("_PartialView
Html.RenderPartial() Name"); }
into the response stream.
Creates an appropriate input
Html.Editor() element based on the model’s @Html.Editor("Name")
data type.
Creates an appropriate input
Html.EditorFor() element for a model property @Html.EditorFor(m => m.Name)
based on its data type.
Displays the value of a model
Html.Display() @Html.Display("Name")
property in a read-only manner.
Html.DisplayFor() Displays the value of a model @Html.DisplayFor(m => m.Name)
property in a strongly typed
manner.
Generates an HTML <label>
Html.Label() @Html.Label("Name", "Full Name")
element for a field.
Generates an HTML <label>
Html.LabelFor() @Html.LabelFor(m => m.Name)
element for a model property.

You might also like