ASP.NET Buttons, OnClientClick, Javascript Confirm, and UpdatePanels

I’m not sure if this problem is a case of me using a button inside an update panel (most likely) or something new with ASP.NET 4.0 (we’ve noticed a lot of random differences between 2.0 and 4.0 in how some controls that seem unchanged between versions are actually rendering different html).

I had a button with a JavaScript confirm message inside an update panel.  So that looked like this:

OnClientClick="return confirm('Are you sure you want to commit your current changes?');"

but no matter what you selected the button would not trigger a postback.  The rendered HTML showed why.

onclick="return confirm('Are you sure you want to commit your current changes?'));
   __doPostBack('cmdCommitChanges','')"

(I wrapped that line for easier reading).

So you can see that we are never even reaching the __doPostBack that is added by asp.net because of the return statement.

To fix this, just chnage your OnClientClick to:

OnClientClick="if (!confirm('Are you sure you want to commit your current changes?')) return;"

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s