Reputation: 1365
I have seen javascript:void(0)
method used on <a>
tags in HTML to hide the target URL of the hyperlinked object. Now I want to do the same on a <asp:HyperLink>
, what should I do?
I am doing ASP.NET and here's the markup:
<asp:HyperLink runat="server" ID="hl1">Blah blah blah</asp:HyperLink>
In the codebehind I specified the NavigateUrl
for hl1
using HttpUtility.UrlDecode
method.
I tried hl1.Attributes[
href]="javascript:void(0)";
in coebehind, does not work. Cannot open the NavigateUrl
anymore.
Upvotes: 0
Views: 2874
Reputation: 21406
You need to store the url you are wanting to navigate to in a hidden field and just set NavigateUrl = "#"
in the markup as shown below. This way when user's cursor hovers over the link, the actual navigate URL will never be displayed at bottom of browser.
Then attach a click
event handler on client-side for the hyperlink which you do by just setting onclick
attribute of the hyperlink to a JavaScript function called navigate
. The actual redirection to a new page is done by this navigate
function.
In this situation, you will only see the URL of current page suffixed with #
. For example, if your current page URL is http://localhost/mysite/view.aspx
then it will show http://localhost/mysite/view.aspx#
at bottom of browser.
Markup needed
<asp:HyperLink runat="server" ID="hl" NavigateUrl="#"
onclick="navigate();">Some Text</asp:HyperLink>
<asp:HiddenField ID="hdnURL" runat="server" Value="http://www.microsoft.com" />
JavaScript needed
<script type="text/javascript">
function navigate() {
window.location.href = document.getElementById("<%=hdnURL.ClientID%>").value;
}
</script>
Another approach that you can use if you must set the NavigateURL for the hyperlink in code-behind is as below. In this approach, you need to remove the NavigateURL before the content renders and store it in a global variable called linkUrl
. The event that fires before the content renders is pageLoad
and we will use that event to do this hack.
Global variable in JavaScript must always be declared outside all methods.
Then on clicking the hyperlink, we can obtain the value from the global variable of linkUrl
and redirect user to that location.
Note: Keep the markup of the hyperlink the same as in first approach. But remove the hidden field from that markup.
<script type="text/javascript">
function navigate(event) {
window.location.href = linkURL;
}
var linkUrl = null;
function pageLoad() {
var link = document.getElementById("<%=hl.ClientID%>");
linkURL = link.getAttribute("href");
link.setAttribute("href","#");
}
</script>
Upvotes: 1