Thursday, May 16, 2013

#aspnet Open link in new tab from server side

 If you create an anchor with a target="_blank", a new window will open when the user clicks the link. However, if you are using a server control, it does not enable opening a new tab directly or through the control click event.

We may be tempted to register the script with
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "redirectscript" + Guid.NewGuid().ToString(), "'" + url + "','_blank');", true);

This does work, but unfortunately the browser will most probably block the popup, since it wasn't called from user action directly.

The solution to this is to add the OnClientClick attribute to the control, configuring the form in which the control is in to run events in a new page, which will happen before actually running the click event.

<asp:LinkButton ID="myButton" runat="server" Text="Click Me!" 
                OnClientClick=" ='_blank';"/>

No comments:

Post a Comment