我想在ASP.NET MVC中呈现一个超文本标记语言链接列表。请注意,这些链接是绝对链接和外部到正在设计的网站。下面的代码可以工作:
<% 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控件?
发布于 2009-10-26 22:23:38
除了在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);
}
}
然后你可以像这样使用它:
<tr>
<td>
<%= Html.Encode(item.Id) %>
</td>
<td>
<%= Html.SimpleLink(item.Url,item.Text) %>
</td>
</tr>
编辑我忘了添加。为了在整个应用程序中使用此HtmlHelper扩展器,您需要在web配置文件中添加以下内容:
<system.web>
<pages>
<namespaces>
<!-- leave rest as-is -->
<add namespace="theNamespaceWhereHtmlHelpersClassIs"/>
</namespaces>
</pages>
</system.web>
发布于 2010-03-25 10:16:17
我喜欢以MVC框架的方式实现它,使用标记构建器类。这样,我就可以传递htmlAttributes
参数来添加类或其他属性:
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));
}
仅仅为了生成一个链接可能看起来有点过分,但这意味着您不必纠结于字符串格式的模式来在链接上插入额外的HTML属性
发布于 2009-10-26 22:14:53
我更喜欢使用
<td><a href="<%= item.Url %>">link</a></td>
在我看来似乎有些“干净”,但我认为你的方法也很好。
https://stackoverflow.com/questions/1624697
复制相似问题