Monday, February 21, 2005

Making a MessageBox in JavaScript

[This was originally posted at]

This is classic - I lose track of how often I see people asking the practical question "How do I create a MessageBox in ASP.Net?" The basic problem is that MessageBoxes occur at the client-side, whereas ASP.Net runs on the server. Therefore you need to have ASP.Net call client-side script, like JavaScript, in order to create the MessageBox.

I had the opportunity to explain this in detail on an article at 4guysfromrolla, at: Although that article was a year ago, I still get regular emails about parts of it. Most people wanted to know how to have a button give a Yes/No prompt, and then trigger the appropriate server event. Eventually to simplify it I wrote a custom-server control and uploaded it to the control gallery on, at: It's a free control, with a link to a demo.

[Update]: I posted the source code for this control:

The gist of it is you:

  1. Have ASP.Net create the JavaScript confirm or prompt using either Me.BtnDelete.Attributes.Add(...) or Page.RegisterStartupScript
  2. Put a runat=server hidden html control on the WebForm.
  3. Clicking a button on the JavaScript messagebox runs a client-side script that (1) sets the hidden control's value property and then (2) submits the form (to return flow to the server).
  4. The ASP.Net classes can access the hidden control's value property at the server.

Essentially, you go from Server to Client by registering the script, you go from client to server by submitting the form, and you make data accessible to both by storing it in a runat=server hidden control.

No comments:

Post a Comment