Call JavaScript Confirm Box from Code-behind in Asp.net

In this asp.net post, i will exaplain how to call javascript cofirm message box from asp.net code-behind page or server-side code.

We use JavaScript confirm box, when we want to notify or varify before doing any action like want to ask before removing records, befor ask payment confirmation.
The javaScript confirm box give user to one chance to varify or confirm action before making any action on web page.

Generally, we use javascript function on button click event using OnClientClick property of button control.
Just write your javascript function name inn OnClientClick property of Button Control to call javascript.

In this asp.net tutorials we will lean to call javascript function in conde-behind page uing c# language and vb.net language.

Here, the code for javascript confirm box function:

<script type="text/javascript">
    function myconfirmbox()
    {
        if (confirm("Are You Sure, want to do this ?"))
        {
            alert("Thank You!"); //Click OK
        }
        else
        {            
            alert("See you later."); //Click CANCEL
        }
    }
</script>

Write above javascript confirm box code in Head tag section.

Now, call the myconfirmbox javascript function from code-behind, create a asp.net web application and design a web page with one server side button control.

Belwo, is the code of server side button control in asp.net, we need to call “btnconfirm_Click” event for call javascript confirm box function.

<asp:Button ID=”btnconfirm” runat=”server” Text=”Call Confirm Box” OnClick=”btnconfirm_Click” />

C#.net Code for call javascript function from code-behind in asp.net:

protected void btnconfirm_Click(object sender, EventArgs e)
{

ScriptManager.RegisterStartupScript(this, this.GetType(), “myconfirmbox”, “myconfirmbox();”, true);

}

vb.net Code for call javascript function from code-behind in asp.net:

Protected Sub btnconfirm_Click(ByVal sender As Object, ByVal e As EventArgs)

ScriptManager.RegisterStartupScript(Me, Me.GetType(), “myconfirmbox”, “myconfirmbox();”, True)

End Sub

Leave a Reply

Your email address will not be published. Required fields are marked *