Explicitly treat link as an absolute link?
I have a control on one of my page which takes some user input (URL) and allows the user to test the link.
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("URL") %>' Target="_blank">Click here to test link</asp:HyperLink>
The problem is if the user puts in the URL "google.com", then the link will be treated as "http://localhost/google.com". I have to put "http://www.google.com" for it to go to the right place.
Is it possible to treat the link like it is an absolute link in all case开发者_如何学Gos?
Try this...
NavigateUrl='<%# Eval("URL", "http://{0}") %>'
Edit: if you want to add check whether it already contain http://
then it should be like..
NavigateUrl=<%# Eval("URL").ToString().Contains("http://") == true ? Eval("URL") :
"http://" + Eval("URL") %>
Is this question of academic nature or do you have a problem to solve?
Firstly, the notion that http://www.google.com is the right place and http://localhost/google.com is incorrect is very wrong.
Your problem as I see is this.
When you pull urls from a datasource there are raw urls which ASP.NET Framework recognizes as relative URL. But you would like them to use their absolute uri.
But the problem is not with the framework as http://localhost/google.com could be a valid URL.
A good example for the same will be the site builtWith. It has valid URLS like http://builtwith.com/facebook.com
And so, the problem is at the place where you have input the data. Why could you not place a small combo so that users could easily add the protocols and then append the url to it as shown below?
Hope this helps.
Based on your comments:
What if it's a secure (https) site or an FTP site?
and
Would that work? What if the input already has
http
in it? What if it's a secure (https) site or an FTP site?
and
The problem is if the user puts in the URL "google.com", then the link will be treated as "http://localhost/google.com". I have to put "http://www.google.com" for it to go to the right place.
Is it possible to treat the link like it is an absolute link in all cases?
You're asking for magic. We don't specialize in magic here. You have to specify something that lets you know that it can become a specific type of domain. Tell them if they don't specify the protocol you will as http:// and the rest of the time it's up to them to specify the protocol. It's all you can do.
As for determining if it's got a protocol, check string.Contains("://")
, since that's what the browser is going to do anyway, more or less.
In your code-behind, check if the user input contains "http://" and append it if it doesn't. You can also use JavaScript to do this.
精彩评论