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

后端 未结 6 883
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 07:45

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

6条回答
  •  悲&欢浪女
    2020-12-29 08:15

    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

提交回复
热议问题