MSMVPS.COM
The Ultimate Destination for Blogs by Current and Former Microsoft Most Valuable Professionals.
ASP.net Button submission control
Sentient thoughts about .NET

Syndication

News

  • Sentient

    My services as a speaker, consultant, trainer and developer are available through Sentient.

    Sentient is a leading provider of software development, consultancy and training services on the Microsoft platform.

    Please feel free to contact me if you have a question about something posted in my blog.

I am often asked how to intercept the postback when an <asp:Button/> is clicked.  The answer is not immediately obvious but once you know the trick it is very straight forward.

What makes this tricky is that an <asp:Button/> renders as <input type="submit" ... /> which means that the page will submit automatically when the button is clicked.

This appears to not give you an opportunity to intercept the click however the first little bit of magic you need to know is that if the button has an "onclick" event that will fire before the page is submitted and the second little bit of magic to know is that the boolean return value from your "onclick" event determines if the page submission continues (return true) or not (return false).

So, this sample code will ask you to confirm the postback and provide you and option to cancel the submittion:

WebForm1.aspx

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="ButtonClick.WebForm1" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<HTML>

    <HEAD>

        <title>WebForm1</title>

        <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">

        <meta name="CODE_LANGUAGE" Content="C#">

        <meta name="vs_defaultClientScript" content="JavaScript">

        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">

    </HEAD>

    <body>

        <form id="Form1" method="post" runat="server">

            <P>Click the button to trigger the confirmButton() javascript function.</P>

            <P><asp:Button id="ButtonSubmit" runat="server" Text="Submit"></asp:Button></P>

            <P><asp:Label id="LabelStatus" runat="server">Status: </asp:Label></P>

        </form>

    </body>

</HTML>

WebForm1.aspx.cs

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

 

namespace ButtonClick

{

    public class WebForm1 : System.Web.UI.Page

    {

        protected System.Web.UI.WebControls.Button ButtonSubmit;

        protected System.Web.UI.WebControls.Label LabelStatus;

 

        private void Page_Load(object sender, System.EventArgs e)

        {

            string jsConfirm = @"<script language='javascript'>

            function confirmButton()

            {

                var agree=confirm('Are you sure you wish to continue?');

                if (agree)

                    return true;

                else

                    return false;

            }

            </script>";

 

            Page.RegisterClientScriptBlock("confirm",jsConfirm);

            ButtonSubmit.Attributes.Add("onclick","return confirmButton();");

        }

 

        #region Web Form Designer generated code

        override protected void OnInit(EventArgs e)

        {

            //

            // CODEGEN: This call is required by the ASP.NET Web Form Designer.

            //

            InitializeComponent();

            base.OnInit(e);

        }

 

        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()

        {   

            this.ButtonSubmit.Click += new System.EventHandler(this.ButtonSubmit_Click);

            this.Load += new System.EventHandler(this.Page_Load);

        }

        #endregion

 

        private void ButtonSubmit_Click(object sender, System.EventArgs e)

        {

            LabelStatus.Text = "Status: ASP Button (Server click)";

        }

    }

}

Easy when you know how!


Posted Wed, Nov 24 2004 9:16 by jonathangreensted
Filed under:

Comments

TrackBack wrote OdeToCode Links For November 28
on Sun, Nov 28 2004 19:29
jonathangreensted wrote re: ASP.net Button submission control
on Tue, Dec 7 2004 17:53
Mr. Greensted,

My hat is off to you. I have been grappling with C# now for a couple of weeks. The issue of hijacking web control events and calling server side script has been difficult for me to understand. Your example was great.

Can't thank you enough for this web page.

best regards
r thomas
juliet_romeo_tango@yahoo.com

jonathangreensted wrote re: ASP.net Button submission control
on Wed, Dec 8 2004 17:35
I have seen this solution (javascript confirm popup) in a couple places and it works, but I am interested in cancelling postback if certain conditions aren't met... i.e if an input field is still blank, or if a select has a certain value. I want to stop the postback without any interaction with the user, but in ways that don't really fit within the MS Validation framework (or rather that apply only some of the time...)

Any thought on intercepting postback via javascript without using the confirm popup?

Thanks,
/c
jonathangreensted wrote re: ASP.net Button submission control
on Wed, Dec 8 2004 17:45
To cancel the postback without using the confirmation pop-up just change the "confirmButton" function to return false based on some other criteria (or true to continue).

I hope this helps.
jonathangreensted wrote re: ASP.net Button submission control
on Mon, Dec 13 2004 18:04
Thank you. This has been very helpful to something I am working on now days.

Manoj
agarwalmk at hotmail dot com
jonathangreensted wrote re: ASP.net Button submission control
on Thu, Dec 16 2004 15:32
Thank you so much for posting this helpful solution.

Best Regards
jonathangreensted wrote re: ASP.net Button submission control
on Wed, Dec 22 2004 15:19
thanks you have solve me a Big Fat Problem!!!

sognant as hotmail
Best Regard!!





jonathangreensted wrote re: ASP.net Button submission control
on Mon, Jan 3 2005 11:40
the solution is very helpful... Thanks so much...

best regards
jonathangreensted wrote re: ASP.net Button submission control
on Wed, Jan 5 2005 10:44
Great solution I can now add client side functionality real easy :)

but i'm still having trouble achieving the following can you help ?

I want to navigate records in a datatable but each time i clicked next / previous the page_load was fired (postback) and the table is trashed.
If I use the above to cancel the post back the button click isnt fired and i cant navigate anyway ?!

any ideas would be greatfully received.

best regards

jugger
jonathangreensted wrote re: ASP.net Button submission control
on Wed, Jan 5 2005 10:53
Jugger

Send me your code and I'll take a look offline.

J.
jonathangreensted wrote re: ASP.net Button submission control
on Sun, Jan 16 2005 19:05
What I am observing is if the "return true;" does not work as desired. I would suggest using __doPostBack('ButtonSubmit',''); instead of "return true".
jonathangreensted wrote re: ASP.net Button submission control
on Wed, Jan 26 2005 9:32
Is it possible to do the same but for other controls i.e. Dropdown list, radio button lists etc

Thanks

Richard
jonathangreensted wrote re: ASP.net Button submission control
on Wed, Feb 16 2005 13:31
Very useful.

However it doesn't seem to work if you disable the submit button in the client side script. This seems to cause the submit to be cancelled.

Any ideas?
jonathangreensted wrote re: ASP.net Button submission control
on Fri, Feb 18 2005 17:10
Very helpful - thanks for taking time to write this.
jonathangreensted wrote re: ASP.net Button submission control
on Mon, Feb 28 2005 12:46
Nice one, very handy, saves messing about with HTML buttons that call ASP buttons which was my previous solution.

Cheers again
jonathangreensted wrote re: ASP.net Button submission control
on Tue, Mar 1 2005 14:27
It is a great trick, but does it work for Mozilla browsers also?
jonathangreensted wrote re: ASP.net Button submission control
on Tue, Mar 1 2005 14:31
There are other browsers?!

Jonathan
jonathangreensted wrote re: ASP.net Button submission control
on Mon, Mar 21 2005 22:31
Hi,

This code has been really very helpful. Could someone please suggest the same if I dont want to use some server control such as a Button. What I want is to have a similar confirm dialog box when the page is loaded and not just when a buttom is clicked.
I would appreciate your help.

Thanks,
Soumitra
jonathangreensted wrote re: ASP.net Button submission control
on Sat, Apr 9 2005 6:54
Wow it's really a great code. but for me whether u have selected any of the item ok or cancel page is always posted to server is there something missed in the code or it may be my mistake.

help me.
thanks.
jonathangreensted wrote re: ASP.net Button submission control
on Sat, Apr 9 2005 7:01
how to get return value provided by function in javascript.

except using hidden variables is there any other way.
TrackBack wrote re:ASP.net Button submission control
on Sat, Apr 16 2005 3:16
^_~
jonathangreensted wrote re: ASP.net Button submission control
on Sat, Apr 23 2005 17:46
Your code always posts. This code is not complete. The solution is bogus.
jonathangreensted wrote re: ASP.net Button submission control
on Thu, May 12 2005 21:09
while this is nice... check out this example which handles things a little nicer (like allowing to disable the submit button when its clicked, but still do the postback)

http://aspzone.com/articles/207.aspx?Pending=true
TrackBack wrote re:ASP.net Button submission control
on Tue, May 17 2005 21:39
^_~,pretty good!csharpsseeoo
jonathangreensted wrote re: ASP.net Button submission control
on Tue, May 24 2005 19:54
Hello

I searched for this too much ..
Many thanks, very very usefull.
jonathangreensted wrote re: ASP.net Button submission control
on Sat, Jun 4 2005 17:09
I had this figured out for a while but what I am strugling with is a similar concept to do with user controls.

for example I have a user control that before it is submitted needs to call a javascript event to prepare it for submission. Now if the submit button was located on the control I could wire the event like in your sample code.

however this control is dropped on to a page to be used in larger form with a submit button. I can't expect users of my control to have to wire up their buttons for my user control so is there a way round this?
jonathangreensted wrote re: ASP.net Button submission control
on Sat, Jun 4 2005 18:04
I've resolved mu issue now and there is actually a very simple solution.

At the page level there is a method called RegisterOnSubmitStatement(id, script)

So in my user control I simply call

Page.RegisterOnSubmitStatement("RenderHTML", "getHTML('txtArticle');")

then when the page postsbacks it will call the necessary code.
jonathangreensted wrote re: ASP.net Button submission control
on Thu, Jun 9 2005 17:44
Hi I tried using it user control written in VB.Net but is not working. My button name in UC is ButtonDelete. Can someone please let me know the code in VB.

Thanks,
Mahesh
jonathangreensted wrote re: ASP.net Button submission control
on Wed, Jun 15 2005 13:00
This was great
jonathangreensted wrote re: ASP.net Button submission control
on Wed, Jun 22 2005 21:01
Great article, it helped a lot. Thanks.


I did one thing different though. I was getting a 'function not defined' javascrpt error, so I removed the following from Page_Load, and put the script block in the <head> of my .aspx file, and it worked just as well.

string jsConfirm = @"<script language='javascript'>
function confirmButton()
{
var agree=confirm('Are you sure you wish to continue?');

if (agree)
return true;
else
return false;
}
</script>";

Page.RegisterClientScriptBlock("confirm",jsConfirm);


jonathangreensted wrote My button is not working on the server but locally it working fine
on Mon, Jul 4 2005 6:29
Hello All,

I uplaaded my application on the hosting server. everything is working fine there but some pages having the problem like button is not working. I used the validation control lets take Required file validator... If i clink the button then validator is fired but i fill the text box then button does not work.
Except some pages, all pages are workign fine on the server.
Can somebody help me out from this proble.

Regards
Amit
TrackBack wrote re:ASP.net Button submission control
on Sun, Jul 17 2005 2:33
ASP.net Button submission controlooeess
TrackBack wrote re:ASP.net Button submission control
on Sun, Jul 31 2005 22:26
ASP.net Button submission controlooeess
jonathangreensted wrote re: ASP.net Button submission control
on Wed, Aug 17 2005 14:52
Hello,

I have a button. When I click it, I want to check something before it shows a popup-window with 2 buttons (OK and Cancel). When I click OK -> do other stuff. When Cancel -> do nothing.

Suggestions
jonathangreensted wrote re: ASP.net Button submission control
on Fri, Sep 2 2005 1:36
I am having an issue with submission of data. My webform contains 3 controls.
Control 1: TextBox
Control 2: RequiredFieldValidator
Control 3: Submit button.

When I click on the Submit button, and if the text box is empty. The error message from the RequiredFieldValidator is shown. So I correct the error by entering some data and hit on Submit button again.
But the event doesn't get fire.

The event is in a seprate abc.aspx.cs.

Any clue.

jonathangreensted wrote re: ASP.net Button submission control
on Tue, Oct 11 2005 4:01
I have the same scenario with Mav above, my user control contains the 3 controls,

control 1: textbox
control 2: requiredfieldvalidator
control 3: submit bitton

I need the confirmation dialog to show only after there's no error from the requiredfieldvalidator.

Any ideas?

Add a Comment

(optional)  
(optional)
(required)  
Remember Me?


Copyright © is the original authors. Blog site is an independent site not sponsored by Microsoft. The Yoda blog server and the Brianna SQL server would like to thank www.ownwebnow.com and www.exchangedefender.com. They wouldn't be here and broadcasting without the generosity of Vlad Mazek and his companies.

Powered by Community Server (Commercial Edition), by Telligent Systems