I would like to render a list of HTML links in ASP.NET MVC. Note that the links are absolute and external to the website being designed. The following code
I like to implement it the way the MVC framework does it, using the tag builder class. This way I can pass through the htmlAttributes
parameter to add things like class or other attributes:
public static MvcHtmlString HtmlLink(this HtmlHelper html, string url, string text, object htmlAttributes)
{
TagBuilder tb = new TagBuilder("a");
tb.InnerHtml = text;
tb.MergeAttributes(new RouteValueDictionary(htmlAttributes));
tb.MergeAttribute("href", url);
return MvcHtmlString.Create(tb.ToString(TagRenderMode.Normal));
}
May seem like overkill just to generate a link, but it means you don't have to muck about with string format patterns to insert additional HTML attributes on the link