SIGN UP MEMBER LOGIN:    
ARTICLE

Html Helper method in ASP.Net MVC application

Posted by Dhananjay Kumar Articles | ASP.NET MVC with C# February 23, 2009
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.
Reader Level:

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.

Login to add your contents and source code to this article
share this article :
post comment
 

not good

Posted by josey oommen May 13, 2012

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

Posted by victor A Dec 28, 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....

Posted by Kapil das Aug 27, 2010

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?

Posted by Frank Brown Aug 30, 2009

I did nt get ur question clearly ... cld u explain it bit clearly ?

Posted by Dhananjay Kumar Aug 30, 2009
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • 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.
    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!
Become a Sponsor