Reputation: 1828
I am currently working on asp.net using C# and I need to show a message box and confirm the input from user and redirect to another page, my code is something like this:
protected void Button1_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>");
sb.Append("if (confirm('YES OR NO?')){ /*some javascript code*/ }");
sb.Append("</script>");
Page.RegisterStartupScript("FocusScript", sb.ToString());
Response.Redirect("Default.aspx");
}
here the problem is directly getting redirected to next page without showing message box.
if i remove Response.Redirect("Default.aspx");
it shows message box successfully. I think the here may be is Response.Redirect()
has higher precedence compared to javascript
I tried using
sb.Append("if (confirm('YES OR NO?')){ window.location.href = \"Default.aspx"; }\");
instead of using Response.Redirect()
but page didn't got redirected, what should I do to resolve this problem?
Upvotes: 1
Views: 1834
Reputation: 2384
add following code on Page_Load
Button1.Attributes.Add("onclick", "if(confirm('do you want to redirect?')){}else{return false}");
now ur button click will first trigger java confirmation modal box.
as for ur Button1 click
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
The idea is - your codebehind Button1_Click event will be triggered only after user confirms by clicking OK
Upvotes: 1
Reputation: 3618
I think it is better to add an attribute to the button at page load and leave the button_click function to just redirect. Something like this (Page Load):
button.attribute.add("onclick","Javascript:confirmFunction();")
in button click just have this:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
finally in JS have this:
<script>
function confirmFunction()
{
if(Confirm("Yes OR NO")
//Add your JS Code
return true; //will pass onto server
else
//Add your JS Code
return false; //will not go to server
}
</script>
HTH
Upvotes: 0
Reputation: 568
There is an option of using adding javascript in client click event
eg:-
<asp:button id="Button1" OnClientClick="javascript:return confirm('Are you sure?');" runat="server" onclick="Button1_Click" />
and then in the code side simple redirect the page.
Upvotes: 4
Reputation: 52241
Confirm
is a JavaScript function and it executes on client side. After you register it, you immediately redirect to another page, and so the function is never executed.
Upvotes: 1
Reputation: 2700
Do you absolutely need to handle this on the server side? Indeed this is where quite a simple thing is getting confusing.
If you could, for instance, handle it with Javascript / jQuery, you could do something simple like:
$('#Button1').click(function(){
if (confirm("Yes or No?")){
window.location = "/default.aspx";
}
});
Upvotes: 6