Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » ASP.NET MVC & JQuery » Html Helper method in ASP.Net MVC application

Html Helper method in ASP.Net MVC application

This article discusses what an HTML Helper method is and how to create and user it in an application built based on ASP.NET MVC Framework.

Author Rank :
Page Views : 25436
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Html Helper:

  • To add content to VIEW of Asp.net MVC application, Html Helper is being used.
  • This is nothing but a method which returns string.
  • Html Helper could we used to generate standard HTML elements like Text Box, Label etc.
  • All Html helper are called on the Html property of view. For example to render a Text Box we call Html.TextBox() method.
  • Using Html helper method is optional. Its purpose is to reduce scripting code.

The ASP.NET MVC framework includes the following set of standard HTML Helpers (this is not a complete list):

  • Html.ActionLink()
  •  Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.EndForm()
  • Html.Hidden()
  • Html.ListBox()
  • Html.Password()
  • Html.RadioButton()
  • Html.TextArea()
  • Html.TextBox()

Creating Html Helper method

Custom Html Helper method could we created in two ways

  1. Using static method.
  2. By extension method.

Using static method:

The easiest way to create custom Html helper method is create static method and return a string. Here we are going to create a Html helper method, which will render a label element of Html.

Step 1:

Add a new folder called Helpers in Asp.Net MVC application.

Step 2:

Add a class in newly created Helpers folder. Right click at folder and then add class named LableHelper.cs

ViewHelper.gif

Step 3:

Now add static method in this class called Label. This method will return string and will take two string parameters named target and text.
Code will be like below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication2.Helpers
{
    public class LabelHelper
    {
        public static string Label(string target, string text)
        {
            return String.Format("<label for= '{0}'>{1}</label>",target,text);
        }
    }
}


Step 4:

Now, we are going to use Label Html helper in view or aspx page.

View\Home\Index.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="MvcApplication2.Helpers" %>
<asp:Content ID="indexHead" ContentPlaceHolderID="head" runat="server">
    <title>Home Page</title>
</asp:Content>

 <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%= Html.Encode(ViewData["Message"]) %></h2>
    <p>
        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
    </p>
    <div>
    <%using(Html.BeginForm())
      { %>
       
        <%=LabelHelper.Label("firstName","Firstname") %>   
       
      <% } %>
    </div>
</asp:Content>

In above code couples of things are worth noticing.

  1. We have included Namespace for Html Handler method of Label.
  2. Html.BeginForm is inside using , such that after rendering form will get closed.
  3. LabelHelper.Label is preceded by <%=.

As Extension method:

       public static class LabelExtensions

        {
            public static string Label(this HtmlHelper helper, string target, string text)

            {
                return String.Format("<label for='{0}'>{1}</label>", target, text);

            }

        }

In above code fact noticing are

  1. First parameter to Html Helper method is this . In case of extension method always first parameter is class on which we are extending the method.
  2. Extended method enables us to add new method in existing class.
  3. Here class is static class. We must define Extension method with static class.
  4. Extension method will be read be Intellisense like other method of the class.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Dhananjay Kumar
I write few articles on Microsoft technologies. Read my blog at . | Mincracker MVP | Microsoft MVP
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Mindcracker MVP Summit 2012
Become a Sponsor
 Comments
ActionLink by Frank On August 28, 2009
Can someone explain to me where ActionLink and RouteLink are in this rollout of MVC? I see examples everywhere but I cannot find them in Intellisense when I type 'Html.'
Reply | Email | Modify 
Re: ActionLink by Dhananjay On August 30, 2009
I did nt get ur question clearly ... cld u explain it bit clearly ?
Reply | Email | Modify 
Re: Re: ActionLink by Frank On August 30, 2009
I am reading a tutorial that gives this example:

<body>
   <h1>New Year's Party</h1>
   <p>
      <%= ViewData["greeting"] %>! We're going to have an exciting party.
      (To do: sell it better. Add pictures or something.)
   </p>
   <%= Html.ActionLink("RSVP Now", "RSVPForm") %>
</body>

The helper Html.ActionLink and related HtmlRouteLink are cited in this tutorial but when i try to access them, they don't exist. are they supposed to be there? is anyone else trying to access them and finding they are missing too?

Reply | Email | Modify 
Editable Grid View in ASP.net MVC by Kapil On August 27, 2010
Sir, Can you help me out in implementing something like this as done in  http://www.mcsoftware.biz/EditableGrid/  in ASP.net MVC technology. I am completely  a new bee to Asp.net MVC and i am now really  getting things on. I have a normal list view where i retrieved a set of data from the database and the "EDIT" & "DELETE" links. when i click on the edit then the Textboxs should appear on the data where in i can edit that and save the data . An option for appending the data to the list is also required. When i click "ADD" then the text boxes for the fields should appear where in i can input data to be added to the list. Can you give any idea of how this can be done in ASP.net MVC....
Reply | Email | Modify 
CheckBox by victor On December 28, 2010
Hi ... can u Help me how to store check box value into DB, if i check the check box then boolean value will be stored in db as True else False .How it is create in MVC Frame Work with ADO.Net EF.. please help me... Thank u.. Regards Victor
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.