简体   繁体   中英

Javascript confirm box in C# code behind

I am trying to show a javascript confirm box in the middle of some server side code and after getting user confirmation continue processing but confirm box does not show up. I even wrote some sample code but no success.

after some server processing I need to ask user a question and after user confirmation continue some other server code. it seems to be very simple. even alert box work. How can I solve it?

please note that I can not call javascript confirmbox straight from buttonclick I need to do some serverside code and if that was ok then I want to show a confirmbox for continuation.

here is the code

<asp:Button ID="btn_deletefromDB" runat="server" OnClick="btn_deletefromDB_Click"  Text="Delete from Datatbase);" />


protected void btn_deletefromDB_Click(object sender, EventArgs e)
{

         //Delete service from Database 
        // some server side processing code
        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "return confirm('Do you want to delete it from runtime too? Click OK to proceed.');", true);
        Label1.Text = "delete from runtime confirmed";
        // continue and delete from runtime
        //bla bla bla

}

您应该将它添加到Button1 OnClientClick事件中,而不是在代码隐藏中触发它,如下所示:

<asp:Button ID="Button1" runat="server" OnClientClick="return confirm('Do you want to delete it? Click OK to proceed.');" OnClick="Button1_Click" />

Web applications do not work like this. You cannot ask for user input in the middle of page's server-side life-cycle. This question has to be asked client-side and user's response has to come to the server as part of the page's submitted data.

All ScriptManager.RegisterStartupScript does is contributes to the final html content that will be sent to the client when the page completes request processing. Keep in mind that by the time this html content arrives to client computer the user may have closed the browser and gone home.

Use AJAX to submit query to server and make the server code so that it does it's processing in two parts. I don't have any working examples of this but this is how it would work in general. For posting data to server you can use native AJAX objects in JS or any other library as others suggested and for processing data on the server side you can use generic handlers (ashx) instead of standard web pages.

  1. Send request to the server.
  2. Catch the first part of the processing via JS on the client page.
  3. Show JS window
  4. Submit the other part to server

You'll have to send results of the first part of processing back to the client because server will not be able to connect second request with the first one by default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM