Alex Rivera | Logout

ASP.NET confirm before executing codebehind

Asked 2012-03-23T03:42:47.463
15

I have a form where a user can delete a record, and I want a pop-up message where the user has to click okay to confirm the delete.

Delete button:

<asp:Button ID="btnDelete" runat="server" Text="Delete" UseSubmitBehavior="false" OnClick="btnDelete_Click" OnClientClick="confirmation();" />

Confirmation function:

function confirmation() {
        var answer = confirm("Are you sure you want to delete? This action cannot be undone.")
    }

So right now, clicking the delete button executes the btnDelete_Click Sub in the code behind regardless of whether you click okay or cancel in the pop-up box. I know I can add if (answer) { -- some code here -- } in my javascript function, but is it possible to use javascript to execute code from the codebehind? Or is there another way to do this?

Edit
Report

1 Answer

0

If you want to excute some code in server side without actually making the post back, you have to use ajax to do that.

function confirmation() {
        var answer = confirm("Are you sure you want to delete? This action cannot be undone.")
        if(answer)
        {
           $.post("ajaxserverpage.aspx?item=34",function(data){
              alert(data); 
          });
        } 
        return false; 
    }

and have a page called ajaxserverpage.aspx and in the page load of that page, check the query string and execute your relevant server side code and return some string

   protected void Page_Load(object sender, EventArgs e)
   {
        if (Request.QueryString["item"] != null)
        {
          // read the item and do your stuff here
         Response.Write("Deleted succssfully");
         Response.End();
        }
    }

You can also use generic handler (.ashx) to do your ajax server side processing instead of the .aspx file. I would prefer this method.

answered 2012-03-23T03:49:40.537

Your Answer