Site icon Donner's Daily Dose of Drama

asp:ImageButton with PostBackUrl and OnClientClick event

When an asp:Imagebutton control is used with a client-side event, for instance to show a popup window, and the control is not in an asp:UpdatePanel, the client-side event does not complete because the ImageButton initiates a full post-back. In the browser, for instance with a ShadowBox popping up, it appears that the event fired and the popup starts to render, but then it disappears as the post-back response arrives. Again, this does not seem to be a problem with an asp:UpdatePanel. Today, I found that one of my ImageButtons no longer worked because I had to remove the UpdatePanel around it.

Here is the markup for my broken button:

function popBox(url, x, y)
{
  Shadowbox.open({
    content: url,
    player: "iframe",
    height: y,
    width: x,
    options: { modal: true }
  });
}

<asp:ImageButton ID="btn" SkinID="btn" runat="server" CausesValidation="false" PostBackUrl="" />

And the code-behind:

  btn.OnClientClick = "javascript:popBox('Popup.aspx?....', 790, 550);";

The PostBackUrl attribute is empty, because I don’t want to post back at all, I just want to pop up a ShadowBox. I just wanted to make sure that explicitely clearing it does not prevent the post-back (it does not, so it is not needed).

There are 2 ways to fix this problem. One is to replace the asp:ImageButton control with an asp:Image. The latter does not post back at all, but we need to change the code-behind as follows to make it work:

  btn.Attributes.Add("onclick", "javascript:popBox('Popup.aspx?....', 790, 550);");

The other fix is simpler and better. Keep the ImageButton control, but change the Javascript in the Onclick event handler (this is what ASP.Net generates for OnClientClick) to return ‘false’ by default:

  btn.OnClientClick = "javascript:popBox('Popup.aspx?....', 790, 550);return false;";

Now the client-side event handler can safely finish his work without being interrupted by an unwanted postback.

Exit mobile version