简体   繁体   中英

How to run confirm dialog from codebehind in asp.net

I want to run confirm dialog from code behind. I searched google and what I found is only where message is predefined and where confirm dialog is linked to button onclick event. I can't link my confirm dialog to onclick event, because I need to check the scenario in codebehind and ask user if he wants to continue.

I have 1 button and about 10 different scenarios (with different questions for each one of them), where I want to ask user, if he wants to continue. If he press OK, then I want to continue my code, otherwise I want to cancel.

I create some javascript function

<script type="text/javascript">
    function Confirm() {
        var hidden = document.getElementById("<%=HiddenField1.ClientID %>");
        if (confirm("Test?")) {
            hidden.value = "ok";
            window.location.replace("PrijavaIzpit.aspx");
        } else {
            hidden.value = "cancel";
        }
    }
</script>

which I call from code behind

Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "Confirm();", true);

But problem is, this code only runs, if I put return after the line where I call javascript function.

Is it the right idea? How should I do that? Is it possible with javascript?

Vitor is correct, use AJAX to make calls to your ASP.NET codebehind page. Since you don't have any actual AJAX code above, I'm simply going to point you to Dave Ward's fantastic page where I learned how to do AJAX with jQuery. I encourage you to read his ongoing articles about how to use jQuery with ASP.NET, particularly when he talks about using a Data Transfer Object (which is basically a JSON.stringified JavaScript object which gets deserialized on the codebehind's [WebMethod] , work is done, and the callback provides the data you're looking for).

You don't mention if you're using jQuery or not, but if you are, you can directly adapt his methods, if you're using pure JS, you'll have to figure out how to make the AJAX calls that way. It's not hard, it's just more convoluted.

You may also find this SO answer helpful.

Or for a different take on the problem, this SO answer .

You can't run a confirm dialog from your code behind in a web application scenario. In client side, use javascript to make an ajax call to server side to check the scenario, then, on ajax callback you continue interacting with the user..

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