I have the following code
protected void Button1_Click(object sender, EventArgs e)
{
string strScript = "if(confirm('Do you confirm?')){alert('OK'); }else{alert('cancel')}";
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Confirmation", strScript, true);
}
protected void Button2_Click(object sender, EventArgs e)
{
string strScript = "if(confirm('Do you confirm?')){return false; }else{return true;}";
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Confirmation", strScript, true);
}
Button1 is displaying the confirmation message and then based on my selection respective alert message is appearing.
However when I click Button2 I do not even get the confirmation message.
That's because the code is wrong - you can't have return
outside of a function, it's bad syntax.
You have to attach such code to something, for example to button click event:
Button2.OnClientClick = "return confirm('Do you confirm?');";
Have such code in the Page_Load
event (or directly in the .aspx
) and then clicking the button will trigger confirmation dialog that if cancelled, will cancel the button click.