2012-01-19 14 views
16

Del mismo modo que puedo crear un ActionLink en ASP.NET MVC que apunta a una acción en un controlador (por ejemplo, - @Html.ActionLink("MyDisplayText", "MyAction", "MyController")), me gustaría poder crear un hipervínculo con una url externa explícitamente definida.¿Cómo se puede utilizar HtmlHelper para crear un hipervínculo externo?

Lo que estoy buscando es algo de código como @Html.HyperLink("stackoverflow", "http://www.stackoverflow.com/") que genera este código HTML: <a href="http://www.stackoverflow.com/">stackoverflow</a>

Si esto no es posible, siempre puedo simplemente escribir el código HTML a mano.

(Esta es mi primera pregunta StackOverflow. Qué emocionante.)

+0

Bienvenido a bordo, no se olvide de votar arriba/abajo y marque las respuestas según corresponda. Descubrirá que obtendrá respuestas mucho mejores si su% de respuestas aceptadas es alto. – SventoryMang

+0

¡Gracias! Los votos arriba/abajo requieren 15 de reputación, así que no puedo hacer eso todavía, pero lo tendré en cuenta. –

Respuesta

16

Un ayudante personalizada podría tener este aspecto:

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)); 
     } 
    } 
} 

mayo ¡este será el primero de muchos HtmlHelpers personalizados que use!

+1

¡Muchas gracias! Su ejemplo produce el HTML: '< a href = ' stackoverflow.com ' > desbordamiento de pila </a >' –

+0

he cambiado el tipo de retorno a MvcHtmlString y funcionó muy bien. –

+0

Ah, eso es correcto. Lo siento, lo olvidé. Edité mi respuesta. – jkokorian

1
public static class HtmlHelpers  
{ 
    public static string Hyperlink(this HtmlHelper helper, string href, string text) 
    { 
     String.Format("<a href=\"{0}\">{1}</a>", href, text); 
    } 
} 

va a funcionar. Usar esto en HtmlHelper denota un método de extensión. Además, si quieres ser el estilo MVC-ish super cool, puede utilizar las opciones TagBuilder e incluso de suministro, tales como el objetivo:

public static MvcHtmlString Script(this HtmlHelper helper, string href, string text, bool openInNewWindow = false) 
    { 
     var builder = new TagBuilder("a"); 
     builder.MergeAttribute("href", href); 
     if(openInNewWindow) 
     { 
      builder.MergeAttributes("target", "_blank"); 
     } 
     builder.SetInnerText(text); 
     return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal)); 
    } 
+0

los métodos de extensión deben ser estáticos y deben declararse en una clase estática –

+0

Gracias, se estaba quedando sin memoria. – SventoryMang

+0

Gracias por la ayuda. –

0

necesita una extensión html ayudante

 

public static class HtmlHelpers 
{ 
    public static string HyperLink(this HtmlHelper html, string text, string href) 
    { 
    return string.Format(@"<a href="{0}">{1}</a>", href, text); 
    } 
} 
 

13

Esta pregunta se hace varios años y fue concebido como una respuesta para ASP.NET MVC V2. Probablemente haya formas mejores y mejores para hacer esto ahora, y le sugiero encarecidamente que considere mirar el answer de @ jkokorian. Esta es una buena manera de mostrar lo que podría hacer, no lo que debería do!

nada terriblemente nuevo que añadir, sino que tienden a utilizar object de parametros opcionales en ayudantes HTML y añadir new RouteValueDictionary(obj) lo que les convierte en una KVP que se pueden agregar con MergeAttributes.

Código:

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)); 
    } 
} 

uso a la vista:

constructor básica:

@Html.ExternalLink("http://www.example.com", "Example!") 

Con atributos HTML:

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

Con HTML y atributos de datos:

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

Las pruebas unitarias:

[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>"); 
} 
0

no pude conseguir las soluciones anteriores para trabajar e hizo algo mucho más simple.

CONTROLADOR

Contracts model = db.Contract 
ViewBag.Link = "<a href='" + model.Link + "'>View Link</a>"; 

VISTA

1

vieja pregunta: ¿Pero respuesta simple - no estoy seguro si esto era siempre una solución.

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

hace el truco muy bien, aunque posiblemente un poco exagerado.

Cuestiones relacionadas