Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

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

, 17 Jun 2014
Rate this:
Please Sign up or sign in to vote.
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.

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:

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.

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

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

  • Html.BeginForm
  • Html.EndForm
  • Html.TextBox
  • Html.TextArea
  • Html.Password
  • Html.Hidden
  • Html.CheckBox
  • Html.RadioButton
  • Html.DropDownList
  • 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:

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.

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.

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.

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.

@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.

Lets run the application and see the result:

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)

Share

About the Author

Rahul Rajat Singh
Software Developer (Senior)
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[^]
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
AnswerArticle of the Day on Microsoft's site PinmvpRahul Rajat Singh22-Jul-14 21:08 
GeneralMy vote of 5 PinprofessionalMihai MOGA20-Jul-14 4:35 
QuestionHelper class PinmemberPiyushVarma17-Jul-14 6:33 
GeneralMy vote of 5 PinmemberAJSON13-Jul-14 5:45 
GeneralHow to position fields on view? PinmemberMember 108786111-Jul-14 7:59 
AnswerRe: How to position fields on view? Pinprotectorthatraja15-Jul-14 3:48 
GeneralMy vote of 3 PinmemberAlbertoLeon CSharpMan24-Jun-14 0:25 
QuestionMVC HTML Helpers. PinmemberMember 1087861119-Jun-14 8:46 
QuestionMVC HTML Helpers PinmemberMember 1087861119-Jun-14 8:41 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140926.1 | Last Updated 18 Jun 2014
Article Copyright 2014 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid