问题
I want to use JavaScript Message-Box in ASP.Net with Yes/No option. The scenario is, when I am calling the JavaScript function on a Client_click event of a button, its working fine. But when I am calling this from code behind (C#), it pops-up after complete execution of the code. Here is what I am trying:
protected void Message_Click(object sender, EventArgs e)
{
if (var == 1)
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "open", "Confirm();", true);
}
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Nothing has been selected')", true);
}
}
Even if the condition var == 1 is true, I am not getting the updated value of string confirmValue. However if I call it on "OnClientClick", it works fine. Have gone through almost all the urls but no luck yet.
Any help will be greatly appreciated.
回答1:
Your code will do not wait for the confirmation value at the server side. Page.ClientScript.RegisterStartupScript will just register the client script and that moment that methods execution will be completed. And it will go on with the next line of the code. It is not the responsibility of the server to handle the registered javascript code. So if you want to achieve the Yes/NO
confirmation and wait to server side use the AjaxModelPopupExtender
with the custom code that will give you what you need.
Here you can get more info on how to use the ajaxmodel pop up extender.
回答2:
You should not do it as you are doing. Coder of Code is right. Do client stuff at client side and come to server with some data to process or decision to process.
In your case you just need to write Javascript function and trigger that function when you want. If the response is yes then do postback or Ajax. If not then just stay on page.
Sample javascipt function will be as below-
<script language="javascript" type="text/javasctipt">
function getConfirmation(){
var r = confirm("Press a button!");
if (r == true) {
return true;
} else {
return false;
}
}
</script>
You can directly call this in action like -
return confirm("Confirm Input");
If you want to use nice custom UI then you can use Ajax Modelpopupextender in Ajax control toolkit.
http://www.codeproject.com/Articles/34996/ASP-NET-AJAX-Control-Toolkit-ModalPopupExtender-Co
来源:https://stackoverflow.com/questions/28536366/yes-no-messagebox-in-asp-net