I have this code and I am trying to run it on a .NET platform but it is not working. Does anyone have any idea what is wrong with my code? Thanks. I am using visual studio 2010, and c# programming language.
private void AlertWithConfirmation()
{
Response.Write("<script language='javascript'>");
Response.Write("var x=window.confirm(\"Are you sure you are ok?\")");
Response.Write("if (x)");
Response.Write("window.alert(\"Good!\")");
Response.Write("else");
Response.Write("window.alert(\"Too bad\")");
Response.Write("</script>");
}
Your code produces this:
Note the
elsewindowidentifier that comes from the lack of separator between the commands, which of course does not exist. It will cause an error because the undefined value doesn’t have analertmethod.Some improvements:
typeattribute instead of the deprecatedlangaugeattribute.if).confirmdirectly instead of polluting the global namespace with a variable.:
Note that if you use this within a regular page, it will write the script tag before the doctype tag, which will cause the browser to go into quirks mode, which will most likely mess up your layout. If you want to add scripts to a regular page you should put a
PlaceHolderon the page where you can add it, or use theClientScriptManager.RegisterStartupScriptmethod.