Saturday, 9 October 2010 18:25 by
SyntaxC4
My good friend John MacIntyre [@JohnMacIntyre] was curious about how to add additional mark-up to an MVC Helper Method. This can be achieved by using Extension methods.
There are a few namespaces or classes that you will want to keep in mind when creating new HtmlHelper Methods of your own.
For this example I will be showing how to create the following mark-up in an extension:
<a href="[action-link]"><span>[action-link text]</span></a>
To get this started I’ll make a static class called HtmlExtensions, this is where I will build my library of ASP.NET MVC Extensions. I’ll be creating an extension method called ActionLinkWithSpan which will Extend the HtmlHelper Class. Let’s take a look:
namespace Net.SyntaxC4.Blog.Examples
{
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
public static class HtmlExtensions
{
public static MvcHtmlString ActionLinkWithSpan(this HtmlHelper html,
string linkText,
string actionName,
string controllerName,
object htmlAttributes)
{
RouteValueDictionary attributes = new RouteValueDictionary(htmlAttributes);
TagBuilder linkTag = new TagBuilder("a");
TagBuilder spanTag = new TagBuilder("span");
spanTag.SetInnerText(linkText);
// Merge Attributes on the Tag you wish the htmlAttributes to be rendered on.
//linkTag.MergeAttributes(attributes);
spanTag.MergeAttributes(attributes);
UrlHelper url = new UrlHelper(html.ViewContext.RequestContext);
linkTag.Attributes.Add("href", url.Action(actionName, controllerName));
linkTag.InnerHtml = spanTag.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(linkTag.ToString(TagRenderMode.Normal));
}
}
}
I used the TagBuilder Class to help create the html elements I wanted to output. The UrlHelper class (which in a MVC View is the Url Property) quite easily creates the link we need based on the input parameters provided.
To use this in our View to generate our link we simply import the namespace it was placed in (or add it to the pages/namespaces section in the web.config) then select it from the intellisense (or type out the Method name) using the Html Property.
<%: Html.ActionLinkWithSpan("Navigate Here", "Index", "Home", new { id="myLink", @class="link" })%>
Well John, I hope this is very helpful.
Happy Coding!