Click here to Skip to main content
16,016,744 members
Articles / Web Development / ASP.NET
Article

An Absolute Beginner's Tutorial on HTML Helpers and Creating Custom HTML Helpers in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.74/5 (53 votes)
17 Jun 2014CPOL4 min read 296.1K   3.2K   64   22
In this article we will try to understand HTML helper methods. We will also see how we can implement custom HTML helpers.

Introduction

In this article we will try to understand HTML helper methods. We will also see how we can implement custom HTML helpers.

Background

People coming from the asp.net web forms background are used to putting the ASP.NET server control on the page using the toolbox. When we work with ASP.NET MVC application there is no toolbox available to us from where we can drag and drop HTML controls on the view. In MVC, if we want to create a view it should contain HTML code for specifying the mark up. MVC Beginners(specially with Web forms background) finds this a little troubling.

ASP.NET MVC team must have anticipated this problem and thus to ease this problem, the ASP.NET MVC framework comes with a set of HTML Helper methods. These helpers are simple functions that let the developer to specify the type of HTML needed on the view. This is done in C#. The final HTML will be generated by these functions at the runtime i.e. We don't have to worry about the correctness of generated HTML.

Using the code

Built in HTML Helpers

Lets look at how we can use various HTML helper methods. Lets try to create a simple contact us form that will ask the user for his name, email id and his query. we can design this form in simple HTML easily, let us see how we can utilize HTML helper to achieve the same.

Image 1

In the above screenshot we can see that the HTML form is created using a HTML helper function, all the labels on the page are created using helper functions and all the textboxes are also created using helper functions. Now if we run the application and try to see the result:

Image 2

If we want to control the HTML attributes of the generated HTML then we can use the overloaded version of the helper functions. Lets say in the above cove, we want to provide ID to all the labels.

Image 3

If we run the application again and try to look at the generated HTML, we can see the ID values we have specified.

Image 4

Following HTML helpers are built into the ASP.NET MVC framework:

  • Html.BeginForm
  • <code>Html.EndForm
  • <code>Html.TextBox
  • <code>Html.TextArea
  • <code>Html.Password
  • <code>Html.Hidden
  • <code>Html.CheckBox
  • <code>Html.RadioButton
  • <code>Html.DropDownList
  • <code>Html.ListBox

HTML Helpers for strongly typed views

If we are creating a strongly typed view then it is also possible to use the HTML helpers methods with the model class. Let us create a model for the contact us page:

C#
public class ContactInfo
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Query { get; set; }
}

Now let is create a strongly typed view for contact us page using the Html helpers.

Image 5

These helper methods create the output HTML elements based on model properties. The property to be used to create the HTML is passed to the method as a lambda expression. It could also be possible to specify id, name and various other HTML attributes using these helper methods. Following HTML helpers are available to be used with strongly typed views:

  • Html.TextBoxFor
  • Html.TextAreaFor
  • Html.PasswordFor
  • Html.HiddenFor
  • Html.CheckBoxFor
  • Html.RadioButtonFor
  • Html.DropDownListFor
  • Html.ListBoxFor

Creating Custom HTML Helpers

If we want to create our own HTML helpers than that can also be done very easily. There are quite a few ways of creating custom helpers. lets look at all the possible methods.

  1. Creating a static method
  2. Writing an extension method
  3. Using the @helper(razor only)

Let us try to create a simple HTML helper method which will create a marked HTML label. There is a new mark tag in HTML5 specifications. Let us try to create a label which create a label then mark it using the HTML5 mark tag.

Lets try to achieve this using all the above mentioned methods.

Creating a static method

In this approach we can simply create a static class with static method which will return the HTML string to be used at the time of rendering.

C#
namespace HTMLHelpersDemo.Helpers
{
     public static class MyHTMLHelpers
     {
          public static IHtmlString LabelWithMark(string content)
          {
              string htmlString = String.Format("<label><mark>{0}</mark></label>", content);
              return new HtmlString(htmlString);
          }
    }
}

Writing an extension method

In this approach we will write a simple extension method for the built in html helper class. this will enable us to use the same Html object to use our custom helper method.

C#
public static class MyExtensionMethods
{
    public static IHtmlString LabelWithMark(this HtmlHelper helper, string content)
    {
        string htmlString = String.Format("<label><mark>{0}</mark></label>", content);
        return new HtmlString(htmlString);
    }
}

Using the @helper(razor only)

This method is pretty specific to razor view engine. Let us see how this can be done. We need to write this method in the view itself.

C#
@helper LabelWithMarkRazor(string content)
{
    <label><mark>@content</mark></label>
}

Note: By default these helpers will be available in the view they are defined in. If we want to use the razor created helpers in multiple views then we have to put all of them in one view and put that view file in App_Code directory. This way they will be usable from all the views.

Now we have the same html helper method written in 3 different ways, Let us create a simple view and try to use these helper methods.

Image 6

Lets run the application and see the result:

Image 7

Point of interest

In this article we looked at HTML helpers. We have also looked at how we can create custom HTML helpers. This article has been written from a beginner's perspective. I hope this has been informative.

History

  • 18 June 2014: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
QuestionNice work! Pin
Frans Vander Meiren2-Jan-17 7:59
Frans Vander Meiren2-Jan-17 7:59 
QuestionAny Good Comprehensive article for all type of MVC helpers e.g Ajax etc Pin
Vaibhav Agarwal8-Sep-16 19:38
Vaibhav Agarwal8-Sep-16 19:38 
GeneralMy vote of 4 Pin
Umesh AP8-Aug-16 21:12
Umesh AP8-Aug-16 21:12 
GeneralVery Nice Article Pin
M,AqibShehzad16-Jul-16 5:21
professionalM,AqibShehzad16-Jul-16 5:21 
QuestionMissing bits Pin
Rehan Mehdi7-Mar-16 20:08
Rehan Mehdi7-Mar-16 20:08 
AnswerRe: Missing bits Pin
Rahul Rajat Singh7-Mar-16 20:45
professionalRahul Rajat Singh7-Mar-16 20:45 
GeneralMy vote of 5 Pin
Santhakumar M3-Nov-15 3:38
professionalSanthakumar M3-Nov-15 3:38 
QuestionInterface use Pin
udoyen7-Jun-15 7:41
udoyen7-Jun-15 7:41 
AnswerRe: Interface use Pin
Rahul Rajat Singh10-Jun-15 18:12
professionalRahul Rajat Singh10-Jun-15 18:12 
GeneralGood article Pin
Bharath Kumar B18-Feb-15 1:34
Bharath Kumar B18-Feb-15 1:34 
QuestionNice Article for Beginners. Pin
Ramanjaneyulu Kondaru6-Feb-15 15:03
Ramanjaneyulu Kondaru6-Feb-15 15:03 
AnswerArticle of the Day on Microsoft's site Pin
Rahul Rajat Singh22-Jul-14 21:08
professionalRahul Rajat Singh22-Jul-14 21:08 
GeneralRe: Article of the Day on Microsoft's site Pin
Umesh AP8-Aug-16 21:11
Umesh AP8-Aug-16 21:11 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA20-Jul-14 4:35
professionalȘtefan-Mihai MOGA20-Jul-14 4:35 
QuestionHelper class Pin
PiyushVarma17-Jul-14 6:33
PiyushVarma17-Jul-14 6:33 
GeneralMy vote of 5 Pin
DataBytzAI13-Jul-14 5:45
professionalDataBytzAI13-Jul-14 5:45 
GeneralHow to position fields on view? Pin
Member 108786111-Jul-14 7:59
Member 108786111-Jul-14 7:59 
AnswerRe: How to position fields on view? Pin
thatraja15-Jul-14 3:48
professionalthatraja15-Jul-14 3:48 
GeneralMy vote of 3 Pin
AlbertoLeon CSharpMan24-Jun-14 0:25
AlbertoLeon CSharpMan24-Jun-14 0:25 
QuestionMVC HTML Helpers. Pin
Member 1087861119-Jun-14 8:46
Member 1087861119-Jun-14 8:46 
QuestionMVC HTML Helpers Pin
Member 1087861119-Jun-14 8:41
Member 1087861119-Jun-14 8:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.