Introduction
In the last article, I explored Creating 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 a 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
{
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 a custom HTML Helper by extending the HtmlHelper class.
Farooq Kaiser
Software Developer (Senior)
http://www.Fairnet.com
Canada
Member
|
12+ years of complete software development life cycle experience for web based applications and multi-tier client-server desktop, primarily using LINQ, WCF, WWF, C#, ASP.NET, XML, XSLT, AJAX, Winforms,Visual Basic, JavaScript, JQuery, Google APIs, C++, VB.NET, C, ATL/COM, Open XML. Extensively involved in the requirement analysis, feasibility study, conceptualization, planning, architecture/design, configuration, development, quality assurance, implementation and release of the software products.
|