5

Based on an answer provided on :

Absolute (external) URLs with Html.ActionLink

I have the following ActionLink:

<li>@Html.ActionLink("ExternalLink", "http://google.com")</li> 

But I still get a 'resource cannot be found error', with :

Requested URL: /Home/http:/google.com

which is tagging /Home onto the absolute path.

UPDATE: I was hoping to wire up an External URL (my own, outside the Web project) and hook up an ActionResult in the controller.. ah, is it because I'm using the HomeController, when I should be using a new one?

What am I doing wrong?

Any help, much appreciated.

Joe

Community
  • 1
  • 1
Joe.Net
  • 1,175
  • 5
  • 19
  • 36

2 Answers2

8

You do not need Razor here. Just use an a tag.

<a href="http://google.com">Link to Google</a>

Update:

For more complicated scenarios you can write a simple HTML helper method like this:

public static class ExternalLinkHelper
{
    public static MvcHtmlString ExternalLink(this HtmlHelper htmlHelper, string linkText, string externalUrl)
    {
        TagBuilder tagBuilder = new TagBuilder("a");
        tagBuilder.Attributes["href"] = externalUrl;
        tagBuilder.InnerHtml = linkText;
        return new MvcHtmlString(tagBuilder.ToString());
    }
}

Just make sure you reference the namespace of this class in your view.

@Html.ExternalLink("Link to Google", "http://google.com")
Ufuk Hacıoğulları
  • 37,978
  • 12
  • 114
  • 156
  • Thanks, please see my further comment, above – Joe.Net Mar 22 '13 at 17:58
  • @Joe.Net I think you still don't have to use html helpers for external URLs. Why do you think you need them? – Ufuk Hacıoğulları Mar 22 '13 at 18:15
  • Thanks - I have a series of Parent urls, each having child urls, all urls of both types are external to the website, so i was hoping to wire up ActionResults to all parent urls (they have no knowledge of there children until loading). If this can't be done, I'll have to tweak my design, which isn't a major issue, but it would be great if there was an elegant(ish) solution.. thanks again – Joe.Net Mar 22 '13 at 19:33
  • @Joe.Net I have added an HTML helper example. – Ufuk Hacıoğulları Mar 22 '13 at 19:57
  • Thank you, I will attempt to apply this to ActionLink – Joe.Net Mar 23 '13 at 08:48
  • I am posting to EBSCOhost from my site, and need to specify a bunch of route values. Which is why the actionlink with raw url overload would be helpful. – Alan Ball Apr 21 '17 at 08:17
2

ActionLink doesn't support absolute urls. The name "action" gives this away. You either need to add your own extension method to HtmlHelper or write the markup yourself.

Paul Fleming
  • 24,238
  • 8
  • 76
  • 113