Displaying alert message from code-behind in ASP.NET

In this post I will explain how to display alert message in ASP.NET from code-behind. We will create a function in the code-behind file to display alert message dynamically.

We will register Javascript dynamically at runtime using ScriptManager.RegisterStratupScript method and display a Javascript alert message from the code-behind.

Create a new ASP.NET Application and add a Button:
<!DOCTYPE html>
<html>
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="bthSayHello" runat="server" Text="Say Hello"
            onclick="bthSayHello_Click" />
    </div>
    </form>
</body>
</html>
Write following in the code-behind page:

C#:

public void Alert(Page page, string message)
{
    string jsString = "alert('" + message + "');";
    ScriptManager.RegisterStartupScript(page, page.GetType(),
            "MyApplication",
            jsString,
            true);
}

protected void bthSayHello_Click(object sender, EventArgs e)
{
    Alert(this.Page, "Hello");
}

VB.NET

    Public Sub Alert(ByVal page As Page, ByVal message As String)
        Dim jsString As String = "alert('" + message + "');"
        ScriptManager.RegisterStartupScript(page,
                                            page.GetType(),
                                            "MyApplication",
                                            jsString,
                                            True)
    End Sub

    Protected Sub bthSayHello_Click(sender As Object, e As EventArgs) Handles bthSayHello.Click
        Alert(Me.Page, "Hello")
    End Sub

Using RegisterStartupScript we can write any Javascript code at runtime. But as we only need to display an alert message, we are only passing alert() method with our message string as the script parameter in the RegisterStartupScript method. Now, we have a server-side function “Alert” that can be called with a Page and a string object to display a message at runtime.
Alert Message Code Behind ASP.NET

2 thoughts on “Displaying alert message from code-behind in ASP.NET

  1. Dave

    Worked great… couldn’t find an example like this anywhere. I wanted to be able to call an alert, pass text and data values to, all from a selectedindexchanged event. This worked like a charm.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *