C# Programming > ASP.NET

ASP.NET MessageBox
C# Function

ASP.NET MessageBox

For veteran C# windows developers, ASP.NET can be a strange new world. I personally found myself stuck on what seemed to be a simple task, displaying a message box in ASP.NET with C# code.

In this article I'll briefly explain the most effect method to write a MessageBox function for ASP.NET.

Server Side MessageBox

A simple solution would be to import the System.Windows.Form reference so you can use the familiar MessageBox.Show("") C# function.

However you have to keep in mind this would be run from the ASP.NET server and not all browsers like that...

Client Side MessageBox

A much more elegant solution is to use ASP.NET to call a client side programming language like JavaScript.

The java code for a message box is as follows:

window.alert("[message here]")

Integrating JavaScript with ASP.NET

The first step to integrating JavaScript in ASP.NET is to set up the script for web format:

<script language='javascript'>
window.alert("[message here]")
</script>

This next step has some flexibility, which is getting C# in ASP.NET to run the script. The way I like to do it is by adding LiteralControl to the Page's Controls with the script. Simple and it works, here is the full C# function:

private void MessageBox(string msg)
{ 
  Page.Controls.Add(new LiteralControl(
"<script language='javascript'> window.alert('"+ msg.Replace("'", "\\'") + "')</script>")); }

Note that the single quot character ' will break the script if it is not properly escaped.

Drawbacks

The drawbacks of such simplicity is simplicity itself. The above C#.NET function will display a message box to a user from an ASP.NET website. However it cannot do much more like display a meaningful Yes-No message box or ask for user input.

Yet this is a great tool for debugging your ASP.NET websites and displaying helpful messages to users. Either way, a MessageBox in ASP.NET can be useful.

Back to C# Article List