Asp.net-Mvc

如何在 Asp.Net MVC 循環中呈現純 HTML 連結?

  • March 26, 2014

我想在 ASP.NET MVC 中呈現 HTML 連結列表。請注意,這些連結是所設計網站的絕對連結和**外部連結。**以下程式碼有效:

<% 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 控制嗎?

你沒有錯過任何東西,但好的方法是在 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>

我喜歡使用標記生成器類以 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 屬性而使用字元串格式模式

引用自:https://stackoverflow.com/questions/1624697