Joe.Net
Joe.Net

Reputation: 1215

Using ActionLink with an Absolute Path

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

Upvotes: 5

Views: 7021

Answers (2)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

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")

Upvotes: 8

Paul Fleming
Paul Fleming

Reputation: 24526

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.

Upvotes: 2

Related Questions