Tuesday, May 25, 2010

Show client side alert message from server side code even when update panel is used

Developers might want to display client side message with information from server side to their users when they have completed some execution at server side. People may try in different way for this purpose.
For example:
Response.Write() method with JavaScript code inside the method:

string mes = "Hello Dhaka";
        Response.Write("<script language=\"javascript\"  type=\"text/javascript\">alert('" + mes + "');</script>");

or ClientScript.RegisterStartupScript() method:

string message = "<script language=\"javascript\"  type=\"text/javascript\">alert('Hello Dhaka');</script>";
        if (!ClientScript.IsStartupScriptRegistered("mes"))
            ClientScript.RegisterStartupScript(this.GetType(), "mes", message);

But these code doesn't work when you use update panel in your page. So better solution is to use ScriptManager.RegisterStartupScript() method. This works whether update panel is used or not. So let's see the code snippet below:

string message = string.IsNullOrEmpty(TextBox1.Text) ? "Please give a text to textbox." : "You have given: " + TextBox1.Text.Trim();
        string script = "<script language=\"javascript\"  type=\"text/javascript\">alert('" + message + "');</script>";
        ScriptManager.RegisterStartupScript(Page, this.GetType(), "AlertMessage", script, false);

With this code snippet you can display a modal message that their data was saved or updated successfully or not.

No comments:

Post a Comment