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.
Html Helper:
The ASP.NET MVC framework includes the following set of standard HTML Helpers (this is not a complete list):
Creating Html Helper methodCustom Html Helper method could we created in two ways
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.csStep 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 belowusing 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.
As Extension method: public static class LabelExtensions
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
Hands on ASP.NET GridView