views:

618

answers:

4

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?

+2  A: 

I think it's good. A simple foreach does the repeater role in MVC.

Mehdi Golchin
+3  A: 

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.

Max
+2  A: 

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>
Misha N.
This allows for HTML injection in both url and text. Use TagBuilder or at least remember to attribute encode the url and html encode the text.
DamienG
Indeed DamienG, tnx.
Misha N.
+2  A: 

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

Glenn Slaven