Skip to content

Javascript Confirm on ASP.Net Button

August 11, 2008

Do you trust users?  I don’t.  Its easier than you think to attach a little javascript confirm popup to a proper ASP.Net server side button.   Thanks to the OnClientClick event handler we can write our javascript right in the line and when the user thinks better of what they’re doing and clicks cancel the POST action will be canceled by the popup returning false.

It’s not a fancy AJAX modal thing but its a quick and easy solution to a common problem.  Hope it helps someone.

CropperCapture[1]

10 Comments leave one →
  1. September 25, 2008 12:00 am

    Just what I was looking for. Thanks! The AJAX control is nice but much heavier than I needed.

  2. Mike permalink
    January 20, 2011 3:54 pm

    Wouldn’t you be better off to say
    OnClientClick=”if(!confirm(‘Are you quite sure?’)) return false; ” ?

    That way you wont return without running validation etc. if the user clicks ok.

    • Dyte permalink
      February 2, 2011 9:16 am

      Yeah, Mike’s variation works for me.
      The original code shows the dialog but ignores the user’s response 🙂

      • August 18, 2011 10:43 pm

        Au contraire… Original code works for me, while Mike’s don’t.

    • April 12, 2011 12:00 pm

      Mike’s code work fine! Thanks Mike :] You’re cool guy ;]

  3. MMK SURI permalink
    June 7, 2011 8:59 am

    Quite Useful Tip; I am developing a project in .net, after completing the project partially I found that MSGBOX control does not work on the web Site, So it has served my purpose. by embedding the script in the html code (client side) I could solve the
    problem
    Thanks

  4. Michael permalink
    November 23, 2011 3:54 pm

    Exactly right Mike’s is correct. The other code will block the request but won’t send the request if OK is clicked.

  5. Rocky permalink
    July 14, 2012 6:47 pm

    When i click delete button without checking an email it should first say “Please select”..But first my javascript function onclientclick is calling as “Are you sure to delete” and if i click ok then it says lbltext = “Please select”. What should I do to validate first the delete button onclick event and then the javascript onclientclick event?

  6. Anonymous permalink
    August 25, 2012 11:14 pm

    This works fine from a button. But I need a confirm message from code. Could someone point the way. Thanks

  7. Johnf522 permalink
    June 7, 2014 4:00 pm

    Very well written article. It will be helpful to anyone who usess it, as well as yours truly dabgecccbedd

Leave a reply to Johnny Cancel reply