如何使用HtmlHelper创建外部超链接?

Log*_*acy 16 c# asp.net-mvc asp.net-mvc-2

就像我可以在ASP.NET MVC中创建指向控制器中的动作(例如 - @Html.ActionLink("MyDisplayText", "MyAction", "MyController"))的ActionLink 一样,我希望能够创建一个带有明确定义的外部URL的超链接.

我正在寻找的是一些像@Html.HyperLink("stackoverflow", "http://www.stackoverflow.com/")这样的代码生成这个HTML:<a href="http://www.stackoverflow.com/">stackoverflow</a>

如果这是不可能的,我总是可以手工编写HTML.

(这是我的第一个stackoverflow问题.多么令人兴奋.)

jko*_*ian 15

自定义帮助器可能如下所示:

namespace System.Web.Mvc {
    public static class HtmlHelperExtensions {
        public static MvcHtmlString Hyperlink(this HtmlHelper helper, string url, string linkText) {
            return MvcHtmlString.Create(String.Format("<a href='{0}'>{1}</a>", url, linkText));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这可能是您使用的许多自定义HtmlHelper中的第一个!


Dan*_*son 14

这个问题已有几年历史了,旨在作为ASP.NET MVC v2的答案.现在可能有更好,更好的方法,我强烈建议你考虑看看@ jkokorian的答案.这只是显示你什么样的一个很好的方法可以做到,不是你应该做的!

没有什么新东西可以添加,但我倾向于object在HTML帮助程序中使用可选参数,并添加new RouteValueDictionary(obj)将它们转换为可以添加的KVP MergeAttributes.

码:

public static class HtmlHelpers {
  public static MvcHtmlString ExternalLink(this HtmlHelper htmlHelper, string url, object innerHtml, object htmlAttributes = null, object dataAttributes = null) {
    var link = new TagBuilder("a");
    link.MergeAttribute("href", url);
    link.InnerHtml = innerHtml.ToString();
    link.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);

    //Data attributes are definitely a nice to have.
    //I don't know of a better way of rendering them using the RouteValueDictionary however.
    if (dataAttributes != null) {
      var values = new RouteValueDictionary(dataAttributes);

      foreach (var value in values) {
        link.MergeAttribute("data-" + value.Key, value.Value.ToString());
      }
    }

    return MvcHtmlString.Create(link.ToString(TagRenderMode.Normal));
  }
}
Run Code Online (Sandbox Code Playgroud)

用法视图:

基本构造函数:

@Html.ExternalLink("http://www.example.com", "Example!")
Run Code Online (Sandbox Code Playgroud)

使用Html属性:

@Html.ExternalLink("http://www.example.com", "Example!", new { title = "Example" })
Run Code Online (Sandbox Code Playgroud)

使用HTML和数据属性:

@Html.ExternalLink("http://www.example.com", "Example!", new { target = "_blank" }, new { id = 1 })
Run Code Online (Sandbox Code Playgroud)

单元测试:

[TestMethod]
public void ExternalLink_Example_ShouldBeValid() {
  //Arrange
  var url = "http://www.example.com";
  var innerHtml = "Example";

  //Act
  var actual = HtmlHelpers.ExternalLink(null, url, innerHtml);

  //Assert
  actual.ToString().Should().Be(@"<a href=""http://www.example.com"">Example</a>");
}

[TestMethod]
public void ExternalLink_Example_WithHtmlAttributes_ShouldBeValid() {
  //Arrange
  var url = "http://www.example.com";
  var innerHtml = "Example";

  //Act
  var actual = HtmlHelpers.ExternalLink(null, url, innerHtml, new { title = "Example!", @class = "myLink", rel = "external", target = "_blank" });

  //Assert
  actual.ToString().Should().Be(@"<a class=""myLink"" href=""http://www.example.com"" rel=""external"" target=""_blank"" title=""Example!"">Example</a>");
}

[TestMethod]
public void ExternalLink_Example_WithDataAttributes_ShouldBeValid() {
  //Arrange
  var url = "http://www.example.com";
  var innerHtml = "Example";

  //Act
  var actual = HtmlHelpers.ExternalLink(null, url, innerHtml, new { title = "Example!" }, new { linkId = 1 });

  //Assert
  actual.ToString().Should().Be(@"<a data-linkId=""1"" href=""http://www.example.com"" title=""Example!"">Example</a>");
}
Run Code Online (Sandbox Code Playgroud)


小智 5

老问题:但是答案很简单-不确定这是否总是解决方案。

@Html.RouteLink("External Link", new {}, new { href="http://www.google.com" })
Run Code Online (Sandbox Code Playgroud)

可以很好地完成技巧-尽管可能有些过大。

  • @Html.RouteLink("外部链接", new {}, new { href="http://www.google.com", target="_blank" }) (2认同)