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 works:
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.Encode(item.Id) %>
</td>
<td>
<%= String.Format("<a href=\"{0}\">link</a>", item.Url) %>
</td>
</tr>
<% } %>
But I am wondering if it's really the right approach. Am I missing some obvious MVC control here?
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
You are not missing anything but good approach is to create extender method on HtmlHelper:
public static class HtmlHelpers
{
public static string SimpleLink(this HtmlHelper html, string url, string text)
{
return String.Format("<a href=\"{0}\">{1}</a>", url, text);
}
}
then you can use it like this:
<tr>
<td>
<%= Html.Encode(item.Id) %>
</td>
<td>
<%= Html.SimpleLink(item.Url,item.Text) %>
</td>
</tr>
[edit] I forgot to add. In order to use this HtmlHelper extender throughout application you need to add the following in the web config file:
<system.web>
<pages>
<namespaces>
<!-- leave rest as-is -->
<add namespace="theNamespaceWhereHtmlHelpersClassIs"/>
</namespaces>
</pages>
</system.web>
I would rather use
<td><a href="<%= item.Url %>">link</a></td>
seems somewhat "cleaner" to me, but I think your approach just as good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With