Ask For Confirmation Before Submitting Data in ASP.NET

Here's a simple way to ask the user for confirmation before submitting data:

C#

protected void Page_Load(object sender, EventArgs e)


{


    string myScript = @"<script type='text/javascript'>


    function askBeforeSubmit() {


    var msg = 'Are you sure?';


    return confirm(msg);


    }


    </script>";


    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MakeSure", myScript);


    form1.Attributes.Add("onsubmit", "return askBeforeSubmit();");


}





VB.NET

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


        Dim myScript As String = "<script type='text/javascript'>" & ControlChars.CrLf & "    function askBeforeSubmit() {" & ControlChars.CrLf & "    var msg = 'Are you sure?';" & ControlChars.CrLf & "    return confirm(msg);" & ControlChars.CrLf & "    }" & ControlChars.CrLf & "    </script>"


        Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "MakeSure", myScript)


        form1.Attributes.Add("onsubmit", "return askBeforeSubmit();")


 


    End Sub





You can also ask for confirmation without writing any code. Just use the OnClientClick event on the button as shown below:


<asp:Button ID="btnMaster" runat="server" Text="Button"


OnClientClick="return confirm('Are you sure?');"/>







About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Nita said...

Hi, perhaps you can help me.

I want to do something similar, but I first read the database and if the data is not fount, I want the client to confirm if he wants to continue.

In my Save_Button event I have this coding:
Dim scriptText As String
scriptText = "return confirm('Do you want to continue?')"
ClientScript.RegisterOnSubmitStatement(Me.GetType(), "ConfirmSubmit", scriptText)

This does not pop up with the Save_button click but the next button click (any button).

Thanks.