2012-01-19 12 views
16

Nello stesso modo in cui posso creare un collegamento ActionLink in ASP.NET MVC che punta a un'azione in un controller (ad esempio, @Html.ActionLink("MyDisplayText", "MyAction", "MyController")), mi piacerebbe poter creare un collegamento ipertestuale con un URL esterno esplicitamente definito.Come si può usare HtmlHelper per creare un collegamento ipertestuale esterno?

Quello che sto cercando è un codice simile @Html.HyperLink("stackoverflow", "http://www.stackoverflow.com/") che genera questo HTML: <a href="http://www.stackoverflow.com/">stackoverflow</a>

Se questo non è possibile, posso sempre appena scrivere il codice HTML a mano.

(Questa è la mia prima domanda StackOverflow. Che emozione.)

+0

Benvenuto a bordo, per favore non dimenticare di votare su/giù e contrassegnare le risposte come appropriato. Scoprirai che otterrai risposte molto meglio se la tua percentuale di risposte accettate è elevata. – SventoryMang

+0

Grazie! I voti Up/Down richiedono 15 reputazione, quindi non posso ancora farlo, ma lo terrò a mente. I metodi di estensione –

risposta

16

Un aiuto personalizzato potrebbe essere la seguente:

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

maggio questo è il primo di molti HtmlHelpers personalizzati che usi!

+1

Grazie mille! Il vostro esempio produce l'HTML: '< a href = ' stackoverflow.com ' > overflow dello stack </a >' –

+0

ho cambiato il tipo di ritorno per MvcHtmlString e ha funzionato grande. –

+0

Ah, giusto. Scusa, ho dimenticato. Ho modificato la mia risposta. – 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); 
    } 
} 

funzionerà. Usarlo in HtmlHelper indica un metodo di estensione. Anche se si vuole essere super cool stile MVC-ish, è possibile utilizzare le opzioni di TagBuilder e anche di alimentazione, come l'obiettivo:

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

devono essere statici e devono essere dichiarati in una classe statica –

+0

Grazie, stava per uscire dalla memoria. – SventoryMang

+0

Grazie per l'aiuto. –

0

è necessario un'estensione html aiutante

 

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

Questa domanda è diversi anni ed è stato inteso come una risposta per ASP.NET MVC v2. Probabilmente ci sono modi migliori e migliori per farlo ora, e ti suggerisco caldamente di prendere in considerazione l'idea di @jkokorian's answer. Questo è solo un bel modo di mostrare cosa si può fare , non quello che si do do!

Niente di terribilmente nuovo da aggiungere, ma io tendo a usare object per params facoltativi su aiutanti HTML, e aggiungere new RouteValueDictionary(obj) che li trasforma in un KVP cui è possibile aggiungere con MergeAttributes.

Codice:

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

Utilizzo in vista:

costruttore di base:

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

Con attributi HTML:

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

con HTML e dati di attributi:

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

Prove di unità:

[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

non ho potuto ottenere le soluzioni di cui sopra per lavorare e ha fatto qualcosa di molto più semplice.

CONTROLLER

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

VISTA

1

vecchia domanda: Ma risposta semplice - non so se questo è stato sempre una soluzione.

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

fa bene il trucco, anche se forse un po 'eccessivo.

Problemi correlati