Search code examples
asp.net-mvcextension-methodsactionlinkhtml.actionlink

Possible to write an Extension Method for ASP.NET's Html.ActionLink() method?


Right now, I'm trying to work around an IE6/7 bug which requires the wrapping of the </a> closing tag with this IE specific comment to make some drop-down menu work:

<!--[if IE 7]><!--></a><!--<![endif]-->

Unfortunately, I cannot inject this directly into my View page code like this:

<%= Html.ActionLink("LinkName<!--[if IE 7]><!--></a><!--<![endif]-->","Action","Controller") %>

As Html.ActionLink will do the safe thing and filter out the comment to prevent a Javascript injection attack. Ok, cool. I'm fine with that. Good design decision.

What I'd like to do is write an Extension Method to this, but the process is eluding me as I haven't done this before.

I thought this would work, but Intellisense doesn't seem to be picking up this Extension method that I've written.

public static class MyLinkExtensions
{
    public static string ActionLinkIE(this HtmlHelper htmlHelper,  
        string linkText, string actionName, string controllerName)
    {
        return LinkExtensions.ActionLink(htmlHelper, linkText, actionName, controllerName).
            Replace(@"</a>", @"<!--[if IE 7]><!--></a><!--<![endif]-->");
    }
}

Any suggestions?

EDIT: Does the class name matter? (in my case, I've called it MyLinkExtensions)

Also, when mousing over <%= Html.ActionLink() %> that is appears to be an Extension Method already. Can I extend an Extension Method?


Solution

  • You probably need to put your Extensions namespace in web.config:

    <pages>      
          <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="System.Linq" />
            <add namespace="Pretzel.Extensions.Html" />
          </namespaces>
    </pages>
    

    That should help the Intellisense.