Using HtmlHelper.GenerateLink

Since the documentation for HtmlHelper.GenearteLink is a bit limited I thought I would document some of my understanding of its usage. The application we are developing uses a static class, called HtmlExtensions, that contains a number of methods to build MvcHtmlString’s. One of those methods was used to generate an anchor tag containing a Controller, Action and Id; for example, Id. Using the MvCHtmlString.Create method the first version of this helper method was written as

return MvcHtmlString.Create(string.Format("<a class="my-link" href="Controller/Action/{0}">{0}</a>", myNumber));

This worked fine in the development environment (VS 2012 with IIS Express 8) but when it was deployed to a virtual directory on the Test server we found that the links would not work because the paths were not being resolved correctly. With experience comes knowledge and I found people who had identified similar problems but using the GenerateLink method; I worked on converting the code above to use that method.

public static MvcHtmlString MyLink(this HtmlHelper helper, string myNumber)
{
    string anchor = HtmlHelper.GenerateLink(helper.ViewContext.RequestContext, 
                        helper.RouteCollection, myNumber, null, "Action", "Controller", 
                        new System.Web.Routing.RouteValueDictionary() { {"Id", myNumber } }, 
                        new System.Collections.Generic.Dictionary<string, object>() { { "class", "my-link" } });
    return MvcHtmlString.Create(anchor);
}

The GenerateLink method listed above produces virtually the same return string value as the initial implementation but this time it takes into account the RequestContext to generate the correct href attribute for the anchor. The other parameters worth noting are the RouteValueDictionary and the htmlAttributes Dictionary. The RouteValueDictionary allows us to define the final part of the Route Url, which in our case was the Id – {controller}/{action}/{id}. The htmlAttributes Dictionary is just a simple Key/Value pair of additional attributes required by the anchor tag. For the code example above to work you would need to replace the “Action” and “Controller” parameters with an actual Action name and Controller name, but other than that this provides a more robust solution to the problem.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s