Display message box in ASP.Net form from codebehind

Mohammed Imtiyaz Dec 08, 2014

In highly interactive web applications, you probably want to let the users know what’s going on when they delete, save, export etc. on the site. Those kinds of status messages are widely used and are often implemented by a JavaScript alert box on the web page. ASP.Net doesn’t natively support JavaScript functions from the code-behind files. You manually have to print out a script tag and add the alert() call to it.

In Windows Forms it is very easy to pop up a status message by calling MessageBox.Show(“message”). It is that kind of object model we want in ASP.Net for printing out JavaScript alerts. We want Alert.Show(“message”) in ASP.Net.

In this article we will learn how to show message box in ASP.Net form from CodeBehind (C# or VB.net)

Let's begin with this small sample.

<html>
<head>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="btnSubit" runat="server" Text="Click Here" />
    </form>
</body>
</html>

Here is the actual we need to write on any button click event to display Message Box

C#

protected void btnSubit_Click(object sender, EventArgs e)
{
    string strAlertMessage = "You clicked the button"; 
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + strAlertMessage + "');", true);
}

VB.net

Protected Sub btnSubit_Click(sender As object ,e As System.EventArgs) Handles btnSubit.Click
    Dim strAlertMessage = "You clicked the button" 
    ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('" + strAlertMessage + "');", true)
End Sub