Tuesday, September 14, 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 = "";
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 = "";
ScriptManager.RegisterStartupScript(Page, this.GetType(), "AlertMessage", script, false);


OR


System.Text.StringBuilder sb = new System.Text.StringBuilder();

sb.Append(@"<script language='javascript'>");

sb.Append(@"var lbl = document.getElementById('lblDisplayDate');");

sb.Append(@"lbl.style.color='red';");

sb.Append(@"</script>");


if (!ClientScript.IsStartupScriptRegistered("JSScript"))

{

ClientScript.RegisterStartupScript(this.GetType(), "JSScript", sb.ToString());

}





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