Edward.K
Edward.K

Reputation: 566

mvc <a href> redirect to other website?

I have implement a link list generate in view and each link is redirect to different website, when i click the link, it will redirect to the format as below:

http://localhost:19150/ModuleView/www.google.com

What i want :

www.google.com

My code:

@for (int x = 0; x < Model[i].Url_Address.Count(); x++)
{
    <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
        <div class="panel-body">
            <a href="@Model[i].Url_Address[x]" class="list-group-item">@Model[i].Url_Name[x]</a>
        </div>
    </div>
}

is that i need to pass it first to action in controller to redirect to the website page? Please correct me if i'm wrong. Highly appreciate!

Upvotes: 1

Views: 1421

Answers (1)

wazdev
wazdev

Reputation: 353

Your link needs to start with "http://" for it to recognise this as an external URL.

You could do something like:

string extLink = @Model[i].Url_Address[x];
if(!extLink.StartsWith(@"http://")) {
     extLink = @"http://" + extLink;
}

......

<a href="@extLink" class="list-group-item">@Model[i].Url_Name[x]</a>

Note: This is for demo purposes only, there are more optimal ways to do this (i.e. do this on the server side), but you should get the idea.

Upvotes: 3

Related Questions