Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 513
Joe.Net Avatar asked Dec 26 '22 07:12

Joe.Net


2 Answers

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")
like image 137
Ufuk Hacıoğulları Avatar answered Jan 07 '23 22:01

Ufuk Hacıoğulları


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.

like image 25
Paul Fleming Avatar answered Jan 07 '23 23:01

Paul Fleming