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.