In this article, I will explore how you can create custom HTML Helpers that you can use within your MVC views. You use HTML helpers in a view to render HTML content. An HTML helper, in most cases, is just a method that returns a string. The ASP.NET MVC framework includes a standard set of helpers that you can use to render the most common types of HTML elements.
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()
In my previous article, I used Html.BeginForm, Html.TextBox, Html.ValidationMessage and Html.TextArea helper methods.
Creating custom HTML helper method
The easiest way to create a new HTML Helper is to create a static method that returns a string. We will create a simple Header control that renders an HTML <H2> tag.
We will create a HeaderHelper class as shown below.
namespace Helpers
{
public static class HeaderHelper
{
/// <summary>
/// Renders an HTML header text
/// </summary>
public static string Text(string headerText)
{
return String.Format("<H2>{0}</H2>", headerText);
}
}
}
I will modify the RSSFeed view from previous article to create a header for the RSSFeed. Notice that the view includes an<%@ imports %> directive that imports the Helpers namespace.
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SyndicationFeed>" %>
<%@ Import Namespace="System.ServiceModel.Syndication"%>
<%@ Import Namespace="Helpers"%>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
RSSFeed
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%= HeaderHelper.Text("Wecome to my RSS Feed in MVC ASP.NET")%>
<%
foreach (var item in ViewData.Model.Items)
{
foreach (SyndicationElementExtension extension in item.ElementExtensions)
{
System.Xml.Linq.XElement ele = extension.GetObject<System.Xml.Linq.XElement>();
Response.Write(ele.Value);
}
string URL = item.Links[0].Uri.OriginalString;
string Title = item.Title.Text;
Response.Write(string.Format("<p><a href=\"{0}\"><b>{1}</b></a>", URL, Title));
Response.Write("<br/>" + item.Summary.Text + "</p>");
} %>
</asp:Content>
Now you can run the project and it will display RSS feed Header as shown below.
Summary
In this article, you learned a method of creating custom HTML Helper by creating a static method that returns a string. In Next article, I will Explore HTML Helpers with Extension Methods.