Search code examples
asp.net-mvcroutelink

RouteLink in HtmlHelper?


How can I make up a RouteLink in a custom HtmlHelper? I know how to make it in a partial view but I want to build up a new link in a custom htmlhelper extension method with the use of a RouteLink. How to accomplish this?

Update: I noticed HtmlHelper.GenerateRouteLink. But what do I need to put in as parameters?


Solution

  • Here's an example. Let's suppose that you want to wrap the links into a div tag with some given class so that your resulting html looks like this:

    <div class="foo"><a href="/home/index">Some text</a></div>
    

    You could write the following extension method:

    public static class HtmlExtensions
    {
        public static MvcHtmlString CustomRouteLink(
            this HtmlHelper htmlHelper, 
            string className, 
            string linkText, 
            object routeValues
        )
        {
            var div = new TagBuilder("div");
            div.MergeAttribute("class", className);
            div.InnerHtml = htmlHelper.RouteLink(linkText, routeValues).ToHtmlString();
            return MvcHtmlString.Create(div.ToString());
        }
    }
    

    which could be used like this:

    <%= Html.CustomRouteLink("foo", "Some text", 
        new { action = "index", controller = "home" }) %>
    

    and this will produce the desired markup. Any other overloads of RouteLink could be used if necessary.