posted 7/3/2010 by Raghav Khunger
Few days back a person asked on the forums on how to open alert box from codebehind or server side. Actually nothing is directly fired from server side in order to show the alert box but actually a script can be registered from server side in the page markup so that as the page loads in the browser an alert is shown. This can be done by "ClientScript.RegisterStartupScript" method. Below is the sample code:
<%@ Page Language="C#" ValidateRequest="false" EnableEventValidation="false" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:Button ID="Button1" runat="server" Text="Test" OnClick="Button1_Click" /> </form> </body> </html> <script runat="server"> private string dynamicTextBoxValue; protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { bool yourcondition = true;//Iam hardcoding to true you can apply your logic here if (yourcondition) { ClientScript.RegisterStartupScript(GetType(), "TestAlert", "alert(\'This is test alert.\');", true); } else { //your logic } } </script>
Now in order to see what the magic the ClientScript.RegisterStartupScript is doing in above script is we need to look the view source of the page when the above page renders. Here is the screenshot of viewsource:
Above you saw a new script tag has been added just above the closing form tag. This has been done by
ClientScript.RegisterStartupScript(GetType(), "TestAlert", "alert(\'This is test alert.\');", true);
You can refer for "ClientScript.RegisterStartupScript" at here http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx
You can also read a related one ASP.NET: How to open confirm box from codebehind or server side
Do let me know your feedback, comments.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18