Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render plain HTML links in Asp.Net MVC loop?

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?

like image 795
Joannes Vermorel Avatar asked Oct 26 '09 13:10

Joannes Vermorel


3 Answers

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

like image 73
Glenn Slaven Avatar answered Sep 22 '22 23:09

Glenn Slaven


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>
like image 33
Misha N. Avatar answered Sep 20 '22 23:09

Misha N.


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.

like image 36
Max Avatar answered Sep 20 '22 23:09

Max