If you find this article useful, consider making a small donation to show your support for this web site and its content.
DiscountASP
AboutMe
About me:
Hi. My name is Farooq Kaiser and I'm a software developer from Toronto, Canada.

Creating HTML Helpers with Extension Methods in ASP.NET MVC framework

by Farooq Kaiser 19. July 2009 10:28

In last article, I explored Custom HTML Helpers by creating a static method that returns a string. In this article, I will explore HTML Helpers with Extension Methods. The HtmlHelper class provides a set of helper methods that generate plain HTML and return the result as a string. The extensions add helper methods for creating forms, rendering HTML controls and rendering partial views and they are located in the System.Web.Mvc.Html namespace. I will create submit confirm button that renders an HTML <input type=”submit tag as SubmitConfirmHelper class shown below.

using System.Web.Mvc; 
namespace Helpers 
{ 
   public static class SubmitConfirmHelper 
   { 
       /// <summary> 
       /// Renders an HTML form submit confirm button 
       /// </summary> 
       public static string SubmitConfirm(this HtmlHelper helper, string buttonText, string alertMessage) 
       { 
           return String.Format("<input type=\"submit\" value=\"{0}\" onClick=\"return confirm('{1}');\" />", buttonText, alertMessage); 
       } 
   } 
} 
Because the SubmitConfirm() method extends the HtmlHelper class, this method appears as a method of the HtmlHelper class in Intellisense as shown below.

The view uses the new Html.SubmitConfirm() helper to render the submit button for a form as shown below.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> 
<%@ Import Namespace="Helpers"%> 
<asp:Content ID="aboutTitle" ContentPlaceHolderID="TitleContent" runat="server"> 
    About Us 
</asp:Content> 
<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server"> 
    <h2>About</h2> 
    <p> 
    <% using (Html.BeginForm()) { %> 
      <%=  Html.SubmitConfirm("Delete", "Do you want to delete?")%> 
    </p> 
     <% } %> 
</asp:Content> 

Now you can run the project and it will render the form as shown below.

Summary 

In this article, you learned a method of creating custom HTML Helper by extending the HtmlHelper class.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

.NET | asp.net

Comments

Jobs Autos Real estate Videos Power by Google
awesome comments