Tuesday, December 20, 2011

JS Alert Message by C# Code

Normally:
public static void ShowMsgBox(string message)
        {           
            Page page = HttpContext.Current.CurrentHandler as Page;
            page.ClientScript.RegisterStartupScript(typeof(Page), "abc", "<script type='text/javascript'>alert('" + message + "');</script>");           
        }

        public static void ShowMsgBoxByPageHide(string message)
        {
            // Cleans the message to allow single quotation marks
            string cleanMessage = message.Replace("'", "\'");
            string script = "<script type='text/javascript'>alert('" + message + "');</script>";

            // Gets the executing web page
            Page page = HttpContext.Current.CurrentHandler as Page;

            // Checks if the handler is a Page and that the script isn't allready on the Page
            if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
            {
                page.ClientScript.RegisterClientScriptBlock(typeof(Page), "alert", script);
            }
        }

For in Update Panel:
public static void ShowMsgBoxInUpdatePanel(string message)
        {
            // Cleans the message to allow single quotation marks
            string cleanMessage = message.Replace("'", "");
            string alertScript = "javascript: alert('" + cleanMessage + "')";
            Page page = HttpContext.Current.CurrentHandler as Page;
            ScriptManager.RegisterStartupScript(page, page.GetType(), "alertScript", alertScript, true);
        }

No comments:

Post a Comment