如何在 Asp.Net MVC 循环中呈现纯 HTML 链接? [英] How to render plain HTML links in Asp.Net MVC loop?

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

问题描述

我想在 ASP.NET MVC 中呈现 HTML 链接列表.请注意,这些链接是所设计网站的绝对链接并且外部.以下代码有效:

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>

[edit] 我忘记添加了.为了在整个应用程序中使用此 HtmlHelper 扩展程序,您需要在 Web 配置文件中添加以下内容:

[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天全站免登陆