In my previous tutorials, I’d explained how to show confirm message box using javascript, how to show alert message from code-behind, how to call javascript function from code-behind, and more amazing tutorials on Asp.net, JavaScript, jQuery here.
Now here in this tutorial, I’ll explain how to show confirm message box from code-behind or server-side using javascript in asp.net with example code-snippet.
We can use a confirm message box if we want the user to verify or accept something before taking any action such as want to ask before deleting records, agree with terms and conditions and so on. For example, insert update delete on gridview data and gridview inline insert update delete are the two posts where I’d implemented confirm message box to delete records using javascript practically.
We can’t 100% show confirmation box from code-behind (without using any third-party controls or jQuery), for that we need the mixture of server-side and client-side support. So, first we need to add the following javascript function in .aspx page in head section, like this:
JavaScript Function
function CallConfirmBox() {
if (confirm(“Confirm Proceed Further?”)) {
//OK – Do your stuff or call any callback method here..
alert(“You pressed OK!”);
} else {
//CANCEL – Do your stuff or call any callback method here..
alert(“You pressed Cancel!”);
}
}
</script>
To call confirm message box function from server-side, we need to define OnClick=”btnCall_Click” event of the asp.net button, like this:
Now we can call that method from code-behind as follows.
For C#:
{
ScriptManager.RegisterStartupScript(this, this.GetType(), “CallConfirmBox”, “CallConfirmBox();”, true);
}
For Vb.net:
ScriptManager.RegisterStartupScript(Me, Me.GetType(), “CallConfirmBox”, “CallConfirmBox();”, True)
End Sub
Example – [.aspx]
Following is the complete HTML Markup code that I used in my .aspx page for this demonstration:
<head id=”Head1″ runat=”server”>
<title>Call Confirm Message Box from code-behin in Asp.net</title>
<script type=”text/javascript”>
function CallConfirmBox() {
if (confirm(“Confirm Proceed Further?”)) {
//OK – Do your stuff or call any callback method here..
alert(“You pressed OK!”);
} else {
//CANCEL – Do your stuff or call any callback method here..
alert(“You pressed Cancel!”);
}
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<h4>
Call Confirm Message Box from code-behin in Asp.net</h4>
<div>
<asp:Button ID=”btnCall” runat=”server” Text=”Click Me!” OnClick=”btnCall_Click” />
</div>
</form>
</body>
</html>
Your code is great!
I remember that when I was a beginner in asp.net I searched this above code. Thanks for your sharing.
It helps a lot. Tks.
How do you do it when you want the code behind to handle to OK or Cancel. Your example shows JS or othe code on the aspx page handling the results