问题
I'm loading links into a gridview, but if they aren't appended with http:// it goes to my server. So something like www.yahoo.com when clicked would go to http://localhost:1304/.../controls/www.yahoo.com. How would I make the browser open a new window to whatever is in the link field when clicked besides doing string manipulation.
I've tried both asp:hyperlinkfield and templatefields
<asp:TemplateField HeaderText="Link">
<ItemTemplate>
<asp:HyperLink runat="server" Text='<% #(Eval("Link")) %>' NavigateUrl='<% #Eval("Link") %>' />
</ItemTemplate>
</asp:TemplateField>
<%--<asp:HyperLinkField DataTextField="Link" HeaderText="Link" SortExpression="Link" DataNavigateUrlFormatString="{0}" DataNavigateUrlFields="Link" Target="_blank" />--%>
Here is some source from the page. The comcast link appends itself to a local destination while the yahoo one is fine.
<td>15478963</td><td>test data - comcast</td><td><a href="Controls/www.comcast.net" target="_blank">www.comcast.net</a></td><td align="right">12/23/2009</td><td>Justen</td>
</tr><tr style="color:Black;background-color:Gainsboro;">
<td>12345678</td><td>Update works!</td><td><a href="http://www.yahoo.com" target="_blank">http://www.yahoo.com</a></td><td align="right">12/23/2009</td><td>Justen</td>
回答1:
This behavior (appending the url to the end of your local server) is caused by the way URL's are interpreted by browsers. To redirect to www.yahoo.com, for example, you have to use an absolute URL, starting with http://.
If your links are pointing to addresses which don't start with http://, then the browser interprets them as relative urls, in relation to the present (local server) location.
So you'll have to do some string manipulation, to check whether the address starts with http:// and add it when it's necessary. Maybe you could do it in the OnRowDataBound event handler for the GridView
Also, to make the links open a new window (or tab) in the browser, you should use the target="_blank" attribute, as pointed out in the previous answer.
回答2:
You need to add a target="_blank" attribute to the link. This will open any link in a new window.
See the href target attribute documentation.
来源:https://stackoverflow.com/questions/1975229/link-loaded-into-my-gridview-try-to-navigate-to-my-local-server