asp.net LinkButton OnClick is not firing with href

2.9k Views Asked by At

I have a LinkButton, it works really well, but when I add a href to the LinkButton, it redirects me to the link without firing the OnClick function.

<asp:LinkButton target="_blank" ID="ad_main_form"  
    OnClick="ad_button_Click" runat="server"  
    CssClass="ad_main_panel" CausesValidation="False" 
    href="https://stackoverflow.com">
</asp:LinkButton>

How to fire OnClick and href together?

2

There are 2 best solutions below

5
Jamshaid K. On

LinkButton has a property with name PostbackUrl instead using href please use this property.

To avoid all this hassle what I would have done is, call a Response.Redirect('url') inside my click handler so it does both the jobs in a cleaner manner.

Update
Unfortunately you cannot open in new tab using Response.Redirect() method, but you can certainly write javascript code to open the url in a new tab. See:

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "openurl", "window.open('http://www.mywebsite.com' ,'_blank');", true);

Alternatively, you can simply do it like this:

Response.Write("<script>window.open('http://www.mywebsite.com', '_blank')</script>");
0
Jamal On

asp:LinkButton does not have an href tag.

You need OnClick for server side and OnClientClick for client side

 <asp:LinkButton ID="ad_main_form"
            runat="server"
            OnClick="ad_button_Click"
            OnClientClick="javascript: window.open('https://stackoverflow.com');">
            Click me
 </asp:LinkButton>

C# Code behind:

 protected void ad_button_Click(object sender, EventArgs e)
    {
        // your code
    }
       

You may also handle it this way and supply a custom JavaScript function to OnClientClick(). See the Navigate(url) function. The code-behind stays the same.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="YourProject.WebForm1" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<script type="text/javascript">
    function Navigate(url) {         
        javascript: window.open(url);
    }
</script>  

<body>
  <form id="form1" runat="server">
    <div>
        <asp:LinkButton ID="ad_main_form"
            runat="server"
            OnClick="ad_button_Click"
            OnClientClick="Navigate('https://stackoverflow.com')" 
            CausesValidation="False">
            Click me
        </asp:LinkButton>
    </div>
  </form>    
</body>

The code has been tested and works fine!