Recent Posts

Tags

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.

Community

Email Notifications

Links

Archives

Sentient thoughts about .NET

Jonathan Greensted's .NET weblog

ASP.net Button submission control

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!

Comments

TrackBack said:

# November 28, 2004 7:29 PM

jonathangreensted said:

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

# December 7, 2004 5:53 PM

jonathangreensted said:

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
# December 8, 2004 5:35 PM

jonathangreensted said:

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.
# December 8, 2004 5:45 PM

jonathangreensted said:

Thank you. This has been very helpful to something I am working on now days.

Manoj
agarwalmk at hotmail dot com
# December 13, 2004 6:04 PM

jonathangreensted said:

Thank you so much for posting this helpful solution.

Best Regards
# December 16, 2004 3:32 PM

jonathangreensted said:

thanks you have solve me a Big Fat Problem!!!

sognant as hotmail
Best Regard!!





# December 22, 2004 3:19 PM

jonathangreensted said:

the solution is very helpful... Thanks so much...

best regards
# January 3, 2005 11:40 AM

jonathangreensted said:

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
# January 5, 2005 10:44 AM

jonathangreensted said:

Jugger

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

J.
# January 5, 2005 10:53 AM

jonathangreensted said:

What I am observing is if the "return true;" does not work as desired. I would suggest using __doPostBack('ButtonSubmit',''); instead of "return true".
# January 16, 2005 7:05 PM

jonathangreensted said:

Is it possible to do the same but for other controls i.e. Dropdown list, radio button lists etc

Thanks

Richard
# January 26, 2005 9:32 AM

jonathangreensted said:

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?
# February 16, 2005 1:31 PM

jonathangreensted said:

Very helpful - thanks for taking time to write this.
# February 18, 2005 5:10 PM

jonathangreensted said:

Nice one, very handy, saves messing about with HTML buttons that call ASP buttons which was my previous solution.

Cheers again
# February 28, 2005 12:46 PM

jonathangreensted said:

It is a great trick, but does it work for Mozilla browsers also?
# March 1, 2005 2:27 PM

jonathangreensted said:

There are other browsers?!

Jonathan
# March 1, 2005 2:31 PM

jonathangreensted said:

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
# March 21, 2005 10:31 PM

jonathangreensted said:

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.
# April 9, 2005 6:54 AM

jonathangreensted said:

how to get return value provided by function in javascript.

except using hidden variables is there any other way.
# April 9, 2005 7:01 AM

TrackBack said:

^_~
# April 16, 2005 3:16 AM

jonathangreensted said:

Your code always posts. This code is not complete. The solution is bogus.
# April 23, 2005 5:46 PM

jonathangreensted said:

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
# May 12, 2005 9:09 PM

TrackBack said:

^_~,pretty good!csharpsseeoo
# May 17, 2005 9:39 PM

jonathangreensted said:

Hello

I searched for this too much ..
Many thanks, very very usefull.
# May 24, 2005 7:54 PM

jonathangreensted said:

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?
# June 4, 2005 5:09 PM

jonathangreensted said:

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.
# June 4, 2005 6:04 PM

jonathangreensted said:

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
# June 9, 2005 5:44 PM

jonathangreensted said:

This was great
# June 15, 2005 1:00 PM

jonathangreensted said:

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);


# June 22, 2005 9:01 PM

jonathangreensted said:

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
# July 4, 2005 6:29 AM

TrackBack said:

ASP.net Button submission controlooeess
# July 17, 2005 2:33 AM

TrackBack said:

ASP.net Button submission controlooeess
# July 31, 2005 10:26 PM

jonathangreensted said:

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
# August 17, 2005 2:52 PM

jonathangreensted said:

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.

# September 2, 2005 1:36 AM

jonathangreensted said:

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?
# October 11, 2005 4:01 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)