Thursday, March 6, 2008

Javascript pop-up errors from asp.net code behind

This is how to generate client side pop-up errors after processing code behind:
It starts with the StringCollection:
private StringCollection clientMessages;

while processing in code behind, add any errors to clientMessages:
if(Error)
clientMessages.Add("you can't do that");

Now in the OnPreRender event...
protected override void OnPreRender(EventArgs e)
{

// Display client messages to browser if any.
if ((clientMessages != null) && (clientMessages.Count > 0))
{
  StringBuilder sb = new StringBuilder(123);
  StringBuilder msg = new StringBuilder(123);
  sb.Append("<script language=\"javascript\" for=\"window\"   event=\"onload\">\n");
  sb.Append("function __ShowClientMessages(){\n");
  sb.Append("alert(\"");
  for (int i=0, j=clientMessages.Count; i<j; i++)
  {
    msg.Length = 0;
    msg.Append(clientMessages[i]);
    msg.Replace("\n","\\n").Replace("\"","\\\"");
    msg.Append("\\n");
    sb.Append(msg.ToString());
    //sb.Append(clientMessages[i].Replace("\n","\\n")).Append("\\n");
  }
  sb.Append("\");\n");
  sb.Append("}\n");
  sb.Append("window.attachEvent(\"onload\", __ShowClientMessages);");
  sb.Append("</script>");
  this.RegisterStartupScript("ClientMessages", sb.ToString());
  sb.Length = 0;
}

And here is how to register the client side script
protected void RegisterStartupScript(string script)
{
  this.RegisterStartupScript(Guid.NewGuid().ToString(),
  "<script language=\"javascript\">\n"
  + script
  +"</script>");
}

And there you have it, javascript pop-up errors from code behind.

No comments: