如何呈现Asp.Net MVC河套平原HTML链接? [英] How to render plain HTML links in Asp.Net MVC loop?

查看:113
本文介绍了如何呈现Asp.Net MVC河套平原HTML链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想呈现ASP.NET MVC HTML链接的列表。请注意,链接是绝对和外部以正在设计的网站。下面code工作:

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>

<% } %>

但我想知道如果它真的是正确的做法。我在这里缺少一些明显的MVC控制?

But I am wondering if it's really the right approach. Am I missing some obvious MVC control here?

推荐答案

您不会错过任何东西,但好的方法是创建的HtmlHelper扩展方法:

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>

我忘了补充。为了使用整个应用此扩展的HtmlHelper您需要添加以下内容的网络配置文件:

[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>

这篇关于如何呈现Asp.Net MVC河套平原HTML链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆