Show and Auto close bootstrap alert messages after few seconds in Asp.Net C#,VB

IntroductionIn this article I am going to explain how to display animated bootstrap alert message box that automatically closes(fade away) with slide up effect after few seconds using both asp.net C# and VB language.
Auto close bootstrap alert messages after few seconds in asp.net


Description:  Here i have demonstrated the use of twitter bootstrap alert to display messages in alert box that auto close after 5 seconds after displaying alert message or can be manually closed by close button provided in alert box 

In previous articles i and explained  What is bootstrap and how to show to show animated bootstrap alert message and Show jquery notification pop up message box and hide after 5 seconds in asp.net and Show message box in asp.net web application like window application and Implement jQuery UI Autocomplete without using web service and Open login form in popup using Ajax ModalPopupExtender 

Implementation: Let’s create a sample web page to demonstrate the implementation of bootstrap alert message boxes in asp.net

Asp.Net C# Section

HTML Source
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    <style type="text/css">
        .messagealert {
            width100%;
            positionfixed;
             top:0px;
            z-index100000;
            padding0;
            font-size15px;
        }
    </style>
    <script type="text/javascript">
        function ShowMessage(message, messagetype) {
            var cssclass;
            switch (messagetype) {
                case 'Success':
                    cssclass = 'alert-success'
                    break;
                case 'Error':
                    cssclass = 'alert-danger'
                    break;
                case 'Warning':
                    cssclass = 'alert-warning'
                    break;
                default:
                    cssclass = 'alert-info'
            }
            $('#alert_container').append('<div id="alert_div" style="margin: 0 0.5%; -webkit-box-shadow: 3px 4px 6px #999;" class="alert fade in ' + cssclass + '"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>' + messagetype + '!</strong> <span>' + message + '</span></div>');

            setTimeout(function () {
                $("#alert_div").fadeTo(2000, 500).slideUp(500, function () {
                    $("#alert_div").remove();
                });
              }, 5000);//5000=5 seconds
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div class="messagealert" id="alert_container">
            </div>

             <div style="margin-top100pxtext-align:center;">
            <asp:Button ID="btnSuccess" runat="server" Text="Submit" CssClass="btn btn-success"
                OnClick="btnSuccess_Click" />
            <asp:Button ID="btnDanger" runat="server" Text="Danger" CssClass="btn btn-danger"
                OnClick="btnDanger_Click" />
            <asp:Button ID="btnWarning" runat="server" Text="Warning" CssClass="btn btn-warning"
                OnClick="btnWarning_Click" />
            <asp:Button ID="btnInfo" runat="server" Text="Info" CssClass="btn btn-info"
                OnClick="btnInfo_Click" />
            </div>
        </div>
    </form>
</body>
</html>


Note: Have you observed I have added the required bootstrap js and css file reference in the Head tag above. It is required to use the bootstrap tools.

I have set the timer using jQuery setTimeout function to automatically close(fade away) the alert after 5 seconds with slide up effect. You can increase or decrease the time as per your choice.

Asp.Net C# Code

public enum MessageType { Success, Error, Info, Warning };
    protected void Page_Load(object sender, EventArgs e)
    {
    } 
    protected void ShowMessage(string Message, MessageType type)
    {
        ScriptManager.RegisterStartupScript(thisthis.GetType(), System.Guid.NewGuid().ToString(), "ShowMessage('" + Message + "','" + type + "');"true);
    }
    protected void btnSuccess_Click(object sender, EventArgs e)
    {
        ShowMessage("Record submitted successfully"MessageType.Success);
    }
    protected void btnDanger_Click(object sender, EventArgs e)
    {
        ShowMessage("A problem has occurred while submitting data"MessageType.Error);
    }
    protected void btnWarning_Click(object sender, EventArgs e)
    {
        ShowMessage("There was a problem with your internet connection"MessageType.Warning);
    }
    protected void btnInfo_Click(object sender, EventArgs e)
    {
        ShowMessage("Please verify your data before submitting"MessageType.Info);
    }

Explanation: In the above code I have created an enum. Enums are strongly typed constants which makes the code more readable and less prone to typing errors. When we have a set of values that are functionally significant and unchanged we can use enum.

Then I have created a function ShowMessage that accepts message and message type as a parameter and calls the javascript function and passes these values to that. Based on these passed values appropriate alert box gets displayed. 
We just need to pass the desired message and the type of message we want to display to the ShowMessage function and all is done. 

Asp.Net VB Section
Design the page same as we designed above in asp.net C# section, but replace the 4 buttons HTML with the following

   <asp:Button ID="btnSuccess" runat="server" Text="Submit" CssClass="btn btn-success" />
            <asp:Button ID="btnDanger" runat="server" Text="Danger" CssClass="btn btn-danger" />
            <asp:Button ID="btnWarning" runat="server" Text="Warning" CssClass="btn btn-warning" />
            <asp:Button ID="btnInfo" runat="server" Text="Info" CssClass="btn btn-info" />

Asp.Net VB Code
Public Enum MessageType
        Success
        [Error]
        Info
        Warning
    End Enum
    Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load 
    End Sub
    Protected Sub ShowMessage(Message As String, type As MessageType)
        ScriptManager.RegisterStartupScript(MeMe.[GetType](), System.Guid.NewGuid().ToString(), "ShowMessage('" & Message & "','" & type.ToString() & "');"True)
    End Sub

    Protected Sub btnSuccess_Click(sender As Object, e As EventArgsHandles btnSuccess.Click
        ShowMessage("Record submitted successfully"MessageType.Success)
    End Sub

    Protected Sub btnDanger_Click(sender As Object, e As EventArgsHandles btnDanger.Click
        ShowMessage("A problem has occurred while submitting data"MessageType.Error)
    End Sub

    Protected Sub btnWarning_Click(sender As Object, e As EventArgsHandles btnWarning.Click
        ShowMessage("There was a problem with your internet connection"MessageType.Warning)
    End Sub

    Protected Sub btnInfo_Click(sender As Object, e As EventArgsHandles btnInfo.Click
        ShowMessage("Please verify your data before submitting"MessageType.Info)
    End Sub

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.
Previous
Next Post »

11 comments

Click here for comments
October 16, 2015 ×

Nice, great help.....

Reply
avatar
October 17, 2015 ×

Thanks vishal for your feedback. I am glad you found this article helpful for you. Stay connected and keep reading for more useful updates on bootstrap and other.

Reply
avatar
Unknown
admin
October 17, 2015 ×

even due some would never write back , be sure we are reading and following your post every day

Reply
avatar
Swapnil
admin
December 08, 2015 ×

Very nicely explained

Reply
avatar
December 12, 2015 ×

Thanks swapnil for your valuable comments. Stay connected and keep reading for more useful updates..:)

Reply
avatar
madhead
admin
January 21, 2016 ×

Would be nice to show this with mvc helpers and razor syntax :)

Reply
avatar
June 01, 2016 ×

muy buen tutorial, lo he usado y funciona a la perfección

Reply
avatar
August 18, 2016 ×

Thanks for you feedback..I am glad you liked this article..stay connected and keep reading...

Reply
avatar
enxto
admin
September 21, 2016 ×

Great Job!!. keep it up.

Reply
avatar
October 14, 2016 ×

Your welcome..Keep reading for more useful articles like this.

Reply
avatar
Farhan
admin
January 03, 2020 ×

excellent work.. thank you

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..