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>
StevesnDob
September 11, 2023 at 6:42 amriviam stock
ethereum price prediction $100,000
Zeytinburnu Nakliye
November 12, 2023 at 9:38 pmNormally I don’t learn article on blogs, but I wish to
say that this write-up very forced me to check out and do it!
Your writing style has been surprised me. Thank you, very nice post.
Zeytinburnu Nakliye
November 14, 2023 at 4:16 amA person essentially lend a hand to make severely posts I would
state. This is the first time I frequented your website page and up
to now? I surprised with the research you made to create this particular
post incredible. Wonderful job!
Zeytinburnu Nakliye
November 14, 2023 at 3:19 pmI needed to thank you for this fantastic read!! I absolutely
enjoyed every little bit of it. I have you bookmarked to check out new things you post…
Zeytinburnu Nakliye
November 17, 2023 at 10:46 amGood day! This is my first visit to your blog! We are a collection of
volunteers and starting a new project in a community in the
same niche. Your blog provided us valuable information to work on. You have done a extraordinary job!
Zeytinburnu Nakliye
November 17, 2023 at 10:42 pmWonderful beat ! I wish to apprentice even as you amend your website,
how could i subscribe for a blog site? The account aided me a acceptable deal.
I were tiny bit acquainted of this your broadcast provided bright clear idea
Zeytinburnu Nakliye
November 18, 2023 at 3:30 pmHey there! I realize this is kind of off-topic but I had to ask.
Does running a well-established blog such as yours take a
massive amount work? I’m completely new to operating a blog but I do
write in my diary daily. I’d like to start a blog so I can easily share my own experience and views
online. Please let me know if you have any ideas or tips for
new aspiring bloggers. Thankyou!
Zeytinburnu Nakliye
November 19, 2023 at 9:12 amThanks a lot for sharing this with all people you really recognise what you are speaking about!
Bookmarked. Please additionally consult with my website =).
We can have a hyperlink exchange arrangement among us
Zeytinburnu Nakliye
November 19, 2023 at 8:11 pmIf you want to grow your knowledge simply keep
visiting this site and be updated with the most up-to-date news update posted here.
Zeytinburnu Nakliye
November 20, 2023 at 5:33 amThanks for the auspicious writeup. It in reality was once
a enjoyment account it. Look complicated to far added agreeable from you!
However, how could we keep up a correspondence?
Zeytinburnu Nakliye
November 20, 2023 at 2:03 pmI savor, lead to I found exactly what I was having a look for.
You have ended my 4 day long hunt! God Bless you man. Have a nice day.
Bye
Zeytinburnu Nakliye
November 21, 2023 at 12:20 amWhat’s Going down i’m new to this, I stumbled upon this I have
discovered It positively helpful and it has helped me out loads.
I’m hoping to contribute & assist different users like its aided me.
Great job.
Zeytinburnu Nakliye
November 22, 2023 at 2:27 amWow, superb weblog format! How lengthy have you
ever been running a blog for? you made blogging glance easy.
The full look of your web site is magnificent, as smartly as the content material!
Zeytinburnu Nakliye
November 22, 2023 at 11:31 amGreat post.
Zeytinburnu Nakliyeci
November 22, 2023 at 11:43 amThis piece of writing offers clear idea in support of
the new people of blogging, that genuinely how to do running a blog.
Zeytinburnu Nakliye
November 23, 2023 at 2:16 pmThanks for another magnificent article. Where else may just anybody get that kind of
information in such a perfect method of writing?
I’ve a presentation subsequent week, and I am on the search for such information.
Zeytinburnu Nakliye
November 24, 2023 at 1:38 amI’ve been browsing on-line greater than 3 hours these days, yet I by no means found any fascinating article like yours.
It’s pretty worth sufficient for me. In my view, if all web
owners and bloggers made just right content material as you probably did, the web
shall be much more useful than ever before.
Zeytinburnu Nakliye
November 24, 2023 at 4:03 pmInformative article, just what I needed.
Zeytinburnu Nakliye
November 25, 2023 at 1:34 amI’m really enjoying the design and layout of your site.
It’s a very easy on the eyes which makes it
much more enjoyable for me to come here and visit more often. Did you
hire out a designer to create your theme? Outstanding work!
Zeytinburnu Nakliye
November 25, 2023 at 10:54 amIf you wish for to take much from this article then you have
to apply these strategies to your won blog.
Zeytinburnu Nakliye
November 25, 2023 at 7:27 pmI am really enjoying the theme/design of your
web site. Do you ever run into any browser compatibility problems?
A number of my blog audience have complained about my blog not working correctly in Explorer but looks great in Opera.
Do you have any recommendations to help fix this issue?
Zeytinburnu Nakliye
November 26, 2023 at 4:55 amThanks for sharing your thoughts about Zeytinburnu
Nakliye. Regards
Zeytinburnu Nakliye
November 26, 2023 at 10:05 pmYour method of describing all in this article is really nice, all be able to effortlessly be aware of it, Thanks a lot.
Nakliye
November 27, 2023 at 11:23 amHi there, this weekend is nice designed for me, because this point in time i am reading this
enormous educational post here at my house.
Zeytinburnu Nakliye
November 27, 2023 at 2:29 pmThis is really attention-grabbing, You’re a very skilled blogger.
I’ve joined your feed and sit up for looking
for more of your excellent post. Additionally, I’ve shared your website in my social networks
Raymon
November 27, 2023 at 11:50 pmGreat posts, Thanks!
Gladis
November 28, 2023 at 1:03 amWonderful info, Thank you!
Nakliye
November 28, 2023 at 5:01 amconstantly i used to read smaller posts which also clear their motive, and
that is also happening with this piece of writing which I
am reading at this place.
Odell
November 28, 2023 at 3:13 pmFine write ups Regards.
Brianne
November 28, 2023 at 3:15 pmMany thanks! Good stuff!
Zeytinburnu Nakliye
November 29, 2023 at 12:16 amHey very interesting blog!
Nakliye
November 29, 2023 at 7:00 amI was more than happy to uncover this website.
I need to to thank you for ones time just for this wonderful read!!
I definitely loved every little bit of it and i
also have you saved to fav to check out new things in your site.
Zeytinburnu Nakliye
November 29, 2023 at 3:47 pmHello There. I found your weblog the use of msn. This is an extremely neatly
written article. I will be sure to bookmark it and come
back to read more of your useful information. Thank you for the
post. I’ll definitely comeback.
Zeytinburnu Nakliye
November 30, 2023 at 1:22 amThis is a topic that is close to my heart…
Cheers! Exactly where are your contact details though?
Nakliye
November 30, 2023 at 4:22 pmRemarkable! Its genuinely amazing paragraph, I have
got much clear idea regarding from this paragraph.
Zeytinburnu Nakliye
November 30, 2023 at 9:54 pmWhat’s up, just wanted to tell you, I loved this article.
It was helpful. Keep on posting!
Nakliye
December 1, 2023 at 6:42 amWhat’s up, I log on to your blogs on a regular basis.
Your writing style is awesome, keep doing what you’re doing!
Zeytinburnu Nakliye
December 1, 2023 at 4:36 pmHi, i read your blog from time to time and i own a similar one and i
was just wondering if you get a lot of spam responses?
If so how do you protect against it, any plugin or anything you can advise?
I get so much lately it’s driving me mad so any help is
very much appreciated.
Nakliye
December 1, 2023 at 5:00 pmFine way of explaining, and pleasant article to obtain data regarding my
presentation focus, which i am going to deliver in college.
Zeytinburnu Nakliye
December 2, 2023 at 1:25 pmJust want to say your article is as amazing.
The clearness in your post is simply excellent and i can assume you’re an expert on this subject.
Fine with your permission allow me to grab your feed to keep up to date with forthcoming
post. Thanks a million and please keep up the rewarding work.
Zeytinburnu Nakliye
December 3, 2023 at 10:23 amI was suggested this website by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my trouble.
You are wonderful! Thanks!
Zeytinburnu Nakliye
December 4, 2023 at 5:03 amHello there! This post couldn’t be written any better!
Reading this post reminds me of my good old room mate!
He always kept chatting about this. I will forward this article to him.
Pretty sure he will have a good read. Thank you for sharing!
Zeytinburnu Nakliye
December 4, 2023 at 10:41 pmGreate post. Keep writing such kind of information on your blog.
Im really impressed by your blog.
Hello there, You’ve done a great job. I’ll definitely digg it
and for my part recommend to my friends. I am confident they will
be benefited from this website.
Nakliye
December 5, 2023 at 11:49 amHello i am kavin, its my first occasion to
commenting anywhere, when i read this post i thought i could also create comment due to this sensible article.
Zeytinburnu Nakliye
December 5, 2023 at 12:31 pmThank you for sharing your thoughts. I truly appreciate
your efforts and I will be waiting for your further post thanks once again.