How to use HTML Helpers in ASP.NET MVC?
Example Code: https://drive.google.com/file/d/1i3fuhlDZ-iWlrvn023UA1WahDNorFUeS/view?usp=sharing
Html helpers are the extension methods of HTML Helper class use to generate html in a view. All Html Helpers are divided into following categories –
- Standard Helpers
- Strongly Typed Helpers
- Template Helpers
View provides you a built in object called HTML of type Html Helper using which we can call those extension methods. Let us first understand standard helpers.
Standard Helpers
Standard helpers are the extension methods of HtmlHelper class when called will generate standard html controls like textbox, checkbox, radiobutton, passwordbox etc. Standard Helpers can be used in any view. Few of the standard helpers are listed below –
TextBox(“name”,[value]) :- is used to generate input type text with specified name as name and id of generated html tag.
Password(“name”) :- is used to generate input type password with name as id and name in generated html tag.
TextArea(“name”,value,rows,cols,htmlattribute):- is used to inject textarea tag with specified value, rows, cols etc.
Checkbox(“name”) :- is used to generate input type=”checkbox”
RadioButton(“name”,value) :- is used to generate input type radio with name and value passed as parameter.
DropdownList(“name”,IEnumerable/SelectList,optionlabel) : – will generate select tag with value and option.
Label(“name”) :- will generate label tag to display read only label.
ActionLink(“text”,”action”,”controller”) :- will generate anchor tag with text when clicked on text it will call specific action of specific controller.
HtmlAttributes: –All helpers will have a html attribute as a parameter, html attribute allow you to inject some additional attribute in html tag those can not be passed as a direct parameter. You can pass here a ananymous object new {attributename=value,attributename=value etc.}
SelectListItem :- is built in class which will help you to define one option or item from the select tag. It can be used in dropdownlist or listbox helper, it has following properties – Text:-used to specify string that will be displayed to the user. Value:- used to specify string that will be used in value property of option. Selected:- will true if the item is selected by user otherwise it will be false.
SelectList:- is again class can be passed in dropdonwlist or listbox helper to create the options. It is wrapper for SelectListItem, it’s constructor will accept IEnumerable collection of selectlistitem or string array as a parameter can be used to generate options.
MultiSelectList: is a class similar to SelectList but used for multiple options.
@model Helpers.Models.Customer
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Pune", Value = "Pune" });
lst.Add(new SelectListItem() { Text = "Mumbai", Value = "Mumbai" });
lst.Add(new SelectListItem() { Text = "Delhi", Value = "Delhi" });
lst.Add(new SelectListItem() { Text = "Noida", Value = "Noida" });
}
<h2> Standard Helpers</h2>
List Box:@Html.ListBox("ct",lst) <br />
ListBox: @Html.ListBox("ct1", new MultiSelectList(new[] {"Noida","Delhi","Pune"})) <br />
Dropdown List: @Html.DropDownList("name",lst,"Select City") <br />
Dropdown List:@Html.DropDownList("cname", new SelectList(new [] {"Pune","Delhi","Noida"}),"Select City")
<br />
Action Link: @Html.ActionLink("Click","SayHello","Test") <br />
Enter Name:@Html.TextBox("EName","Akash",new { style = "background-color:orange", size = "100" }) <br />
Password: @Html.Password("EPass") <br />
Address:@Html.TextArea("Add",null,10,40,new {style="background-color:green"}) <br />
Label :@Html.Label("lbl") <br />
Checkbox:@Html.CheckBox("chk") <br />
Radio Button:@Html.RadioButton("rd","tes") <br>
</body>
</html>
Strongly Typed Helpers
Strongly typed helpers are the helpers those can be used in strongly typed view and will generate the HTML for model property passed as a parameter.
All strongly typed helpers has for suffix and first parameter will be a model property passed in the form of lambda expression and will have other regular parameters.
e.g. TextboxFor(lambda), TextAreaFor(lamda), CheckbocFor(lambda) etc.
@model Helpers.Models.Customer
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Pune", Value = "Pune" });
lst.Add(new SelectListItem() { Text = "Mumbai", Value = "Mumbai" });
lst.Add(new SelectListItem() { Text = "Delhi", Value = "Delhi" });
lst.Add(new SelectListItem() { Text = "Noida", Value = "Noida" });
}
<h2> Strongly typed Helpers </h2>
name: @Html.TextBoxFor(p=>p.CustomerName) <br />
Address :@Html.TextAreaFor(p=>p.Address,5,20,null) <br />
Dropdownlist:@Html.DropDownListFor(p=>p.City,lst,"Select City") <br />
Checkbox: @Html.CheckBoxFor(p=>p.IsActive) <br />
</body>
</html>
Template Helpers
Template helpers are the most intelligent, in template helper we will not tell weather we need the textbox or checkbox etc. we will just tell we need a ui for editing and ui for display using two helpers editor for , display for.
EditorFor(lambda):=> editor for is used if you want to edit the value of model property.
DisplayFor(lambda):=> display for is used if you want to display the value of model property.
You can use the editor and display for in strongly typed helper as follows –
@model Helpers.Models.Customer
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Pune", Value = "Pune" });
lst.Add(new SelectListItem() { Text = "Mumbai", Value = "Mumbai" });
lst.Add(new SelectListItem() { Text = "Delhi", Value = "Delhi" });
lst.Add(new SelectListItem() { Text = "Noida", Value = "Noida" });
}
<h3> Templated Helpers </h3>
Name: @Html.EditorFor(p=>p.CustomerName) <br />
Name :@Html.DisplayFor(p=>p.CustomerName) <br />
Active Flag: @Html.EditorFor(p=>p.IsActive) <br />
Active Flag: @Html.DisplayFor(p=>p.IsActive) <br />
</body>
</html>
How to Create Custom HTML Helpers in ASP.Net MVC?
You can also create a HTML custom helper in ASP.NET MVC. HTML helpers is a extension method HtmlHelper class so we need to create extension method for HTML Helper class.
Create a static class with static method, with first parameter defined using this keyword. In this scenario , the paramter should be of type IHtmlHelper since we need to add the method to HtmlHelper class and it implements interface IHtmlHelper and should return a content type IHtmlContent. In this method you can write any custom logic to create html tag, to generate html tag.
Following example shows how to create custom html helper for image as follows –
Step1 : Create a Folder Custom Helpers and add a class ImageHelper in it with a method GetImage as follows –
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Helpers.CustHelpers
{
public static class ImageHelper
{
public static IHtmlContent GetImage(this IHtmlHelper obj, string s, string w, string h, string a)
{
//string str = "<img src=" + s + " width=" + w + " height=" + h +" alt="+ a+" />";
//return new HtmlString(str);
//tagbuilder will help you to create the tags.
TagBuilder tb = new TagBuilder("img");
tb.MergeAttribute("src", s);
tb.MergeAttribute("width", w);
tb.MergeAttribute("height", h);
return tb.RenderSelfClosingTag();
}
}
}
Step 2: use the namespace in a view by adding @using statement and call the helper method in view as follows –
<!-- using this namespace -->
@using Helpers.CustHelpers
@model Helpers.Models.Customer
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Pune", Value = "Pune" });
lst.Add(new SelectListItem() { Text = "Mumbai", Value = "Mumbai" });
lst.Add(new SelectListItem() { Text = "Delhi", Value = "Delhi" });
lst.Add(new SelectListItem() { Text = "Noida", Value = "Noida" });
}
@Html.GetImage("/images/Ar.jpg","400px","500px","no image")
<h3> Templated Helpers </h3>
Name: @Html.EditorFor(p => p.CustomerName) <br />
Name :@Html.DisplayFor(p => p.CustomerName) <br />
Active Flag: @Html.EditorFor(p => p.IsActive) <br />
Active Flag: @Html.DisplayFor(p => p.IsActive) <br />
<h2> Strongly typed Helpers </h2>
name: @Html.TextBoxFor(p => p.CustomerName) <br />
Address :@Html.TextAreaFor(p => p.Address, 5, 20, null) <br />
Dropdownlist:@Html.DropDownListFor(p => p.City, lst, "Select City") <br />
Checkbox: @Html.CheckBoxFor(p => p.IsActive) <br />
<h2> Standard Helpers</h2>
List Box:@Html.ListBox("ct", lst) <br />
ListBox: @Html.ListBox("ct1", new MultiSelectList(new[] { "Noida", "Delhi", "Pune" })) <br />
Dropdown List: @Html.DropDownList("name", lst, "Select City") <br />
Dropdown List:@Html.DropDownList("cname", new SelectList(new[] { "Pune", "Delhi", "Noida" }), "Select City")
<br />
Action Link: @Html.ActionLink("Click", "SayHello", "Test") <br />
Enter Name:@Html.TextBox("EName", "Akash", new { style = "background-color:orange", size = "100" }) <br />
Password: @Html.Password("EPass") <br />
Address:@Html.TextArea("Add", null, 10, 40, new { style = "background-color:green" }) <br />
Label :@Html.Label("lbl") <br />
Checkbox:@Html.CheckBox("chk") <br />
Radio Button:@Html.RadioButton("rd", "tes") <br>
</body>
</html>