views:

20

answers:

2

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?

A: 

Once you get an instance of the UrlHelper you should be able to do whatever you want to do in your HtmlHelper method

UrlHelper url = new UrlHelper(helper.ViewContext);
runxc1 Bret Ferrier
I will give it a try.
Nyla Pareska
It should be new UrlHelper(helper.ViewContext.RequestContext);
Nyla Pareska
This does not seem to be going the right direction. Any other suggestion?
Nyla Pareska
A: 

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.

Darin Dimitrov
Thank you. I did had some problems at first due to a missing using statement so the RouteLink wasn't known and even Resharper didn't find it correctly. I used the LinkExtensions RouteLink method now.
Nyla Pareska