How to execute server side/codebehind code with Confirmation alert in Javascript

In this article i have explain you How to execute server side code with Confirmation alert in Javascript. Most of the time we need to execute server side/codebehind code after confirmation from user. This article will help you execute the code as per user selection


Most of the time we need to show confirm message in application and with the result of confirmation we need to call server side code. To achieve this type
functionality we need Asp.Net and little bit JavaScript knowledge.


In this article i will explain how to call serverside/code behind code after confirmation prompt, suppose i have a application of reservation system in which i have
to cancel a booked ticket, when i click on 'Cancel' button, Application prompt me about confirmation. On click of 'Yes' i need to delete the database entry
and on click of 'Cancel' i want to increase the counter in database. So in both cases i need to execute database stuff.
I can achieve my task with help of and Javascript

Lets cook with

Things we need:
1. A hidden field (To store the value of confirmation)
2. Javascript function (To prompt user for confirm box)
3. Code behind code (Which will execute after confirmation result)
4. A submit button (To Post form)

Cooking Procedure

add following code to .aspx page with Javascript function under section and add a Hidden field in aspx and

//in aspx add a button and hidden field

//add following 'script' tag in 'Head' section
<script type = "text/javascript">
function askConfirmation()
//use Confirm() method from javascript to prompt user ('Confirm' is inbuilt method of javascript)
if (confirm("Do you want to cancel ticket?"))
hdnConfirm.value = "Yes"; //save result in Hidden field
} else
hdnConfirm.value = "No"; //save result in Hidden field
//Here one thing to keep in mind, that do not use 'return false' from javascript method, which will avoid postaback and your code behind will not execute
after confirmation.

Now we need to write a server side code on submit button click

protected void btnConfirm_Click(object sender, EventArgs e)
//use Request.Form method to collect value of hidden field
string szConfirm = Request.Form["hdnConfirm"];
if (szConfirm == "Yes")
//execute database script for reservation cancel
//execute database script for reservation cancel

So, we have completed easily and accomplish our task

Summing Up

In this article we have seen, how we can call code behind from javascript confirmation box. Still there are lot useful stuff to discuss about javascript
I can cover them one by one as time permits.

Suggestions and Doubts are always welcome.



No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: