Click here to Skip to main content
15,879,326 members
Articles / Web Development / ASP.NET

Bootstrap Alert from ASP.NET Server Side

Rate me:
Please Sign up or sign in to vote.
3.82/5 (9 votes)
1 Apr 2018CPOL3 min read 71.5K   2K   19   7
Showing alert to web users can't be easier than using Bootstrap alert from server side VB.NET

Introduction

For various reasons, alerts are displayed to web users either as information, warning or questions. In Windows Form, the most common method is by calling the MsgBox object function. In ASP.NET, the case is different because the MsgBox does not work on IIS server. JavaScript alerts can be useful though, also Toastr and some other plugins but device variance should be considered when using popups in ASP.NET.

In this situation, I will introduce a piece of procedure to execute Bootstrap alert from server-side.

Image 1

Background

To use this technique, you should understand bootstrap very well so you can debug or transform this logic as you wish.

  1. Learn Bootstrap now from getbootstrap.com
  2. See the Bootstrap Alert section
  3. Bootstrap alert with JavaScript
  4. See how to use font-awesome icon pack

Bootstrap alerts can be dismissed with a close icon and it is rendered in a div on page. It has 4 (five) states which is common in many bootstrap components.

Alert-success

This displays a success message with green background color. Better for passing calm success information to users.

Alert-warning

Displays a warning message to the user with light-orange background. Better for failed actions.

Alert-info

Used to display tips and information to the user with a lightblue background.

Alert-danger

Used to show error messages, critical results like failed database connection, invalid data, wrong input etc.

Icons

Icons for various alerts are used from font-awesome.

The Alert CSS Style

By default, this is the CSS for the alert component as provided by Bootstrap.

.alert {
    padding: 15px;
    margin-bottom: 20px;
    border: 1px solid transparent;
    border-radius: 4px;
}

To use this effectively, we add a CSS property display: block; to make it show in block form (covering the entire 100% width available). To modify this, you should add the rule below to a CSS file or overwrite the bootstrap.css or bootstrap.min.css which is not preferable.

.alert { display: block; }

The BootstrapAlert() Method

We create a public class or module as the case may be in ASP.NET web projects, and add the following enum and method.

Public Enum BootstrapAlertType
        Plain
        Success
        Information
        Warning
        Danger
        Primary
End Enum
  • Plain – Displays the alert without background color, uses default
  • Success – Displays a success alert
  • Information – Displays am information alert
  • Warning – Displays a warning alert
  • Danger – Displays error/critical alerts

These set a fixed type of alert rather than using string, it is easier to call them like this.

Public Shared Sub BootstrapAlert(MsgLabel As Label, Message As String, _
Optional MessageType As BootstrapAlertType = BootstrapAlertType.Plain,
                                     Optional Dismissable As Boolean = False)
        Dim style, icon As String
        Select Case MessageType
            Case BootstrapAlertType.Plain
                style = "default"
                icon = ""
            Case BootstrapAlertType.Success
                style = "success"
                icon = "check"
            Case BootstrapAlertType.Information
                style = "info"
                icon = "info-circle"
            Case BootstrapAlertType.Warning
                style = "warning"
                icon = "warning"
            Case BootstrapAlertType.Danger
                style = "danger"
                icon = "remove"
            Case BootstrapAlertType.Primary
                style = "primary"
                icon = "info"
        End Select

        If (Not MsgLabel.Page.IsPostBack Or MsgLabel.Page.IsPostBack) And Message = Nothing Then
            MsgLabel.Visible = False
        Else
            MsgLabel.Visible = True
            MsgLabel.CssClass = "alert alert-" & _
            style & If(Dismissable = True, " alert-dismissible fade in font2", "")
            MsgLabel.Text = "<i class='fa fa-" & icon & "'></i>" & Message
            If Dismissable = True Then
                MsgLabel.Text &= "<button type='button' _
                class='close' data-dismiss='alert' _
                aria-label='Close'><span aria-hidden='true'>&times;_
                </span></button>"
            End If
            MsgLabel.Focus()
            Message = ""
        End If
    End Sub

Implementing Bootstrap Alert

1. Import the Class

You can do this in two ways. In the sample I have included, the class reference in the Web.config to make it public in all webforms.

<configuration>
  <system.web>
    <compilation debug="true" strict="false" 
    explicit="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />

    <pages>
      <namespaces>
        <add namespace="AppClass" />
      </namespaces>
    </pages>
  </system.web>
</configuration>

Or do this in the webform class level. AppClass is the name of the class having the BootstrapAlert method in App_Code folder.

Imports AppClass

Partial Class _Default

    Inherits System.Web.UI.Page

End Class

2. Add a Label Control to your webform

Next, you should add a label to the page or form.

<asp:Label ID="lblMsg" runat="server" Visible="false"></asp:Label>

On page load, the Label visibility is set to false.

3. Call the BootstrapAlert Method

  • The first parameter is the name of the MsgLabel, in this case “lblMsg
  • Message is the string value to output to the user
  • MessageType is the alert type to show, the values come from the BootstrapAlertType Enum (Default, Success, Information, Warning, Danger, Primary)
  • If Dismissable parameter is set to True, the alert will have a dismiss/close icon to the right for the user to remove it from page.

4. Example Output

BootstrapAlert(lblMsg, "Congrats! You've won a dismissable booty message.", 
	BootstrapAlertType.Success, True)

Image 2

BootstrapAlert(lblMsg, "Sorry! We could not sign you in", _
BootstrapAlertType.Warning, True)

Image 3

BootstrapAlert(lblMsg, "You can also use the exit door", BootstrapAlertType.Information)

BootstrapAlert(lblMsg, "Database connection has failed. _
Pls check issue", BootstrapAlertType.Danger)

Point of Interest

BootstrapAlert can be customized to fit your needs, change the color, the style, icons and more. It is very handy even for beginners.

References

  1. http://getbootstrap.com

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Hallmarkit Business Solutions
Nigeria Nigeria
I am a fullstack .Net Developer (VB.NET/C#/jQuery), studied Computer Science, Instructor, Writer, Speaker.
I build WinForm Apps, Web Apps with ASP.NET MVC + WebForms, Android (using Xamarin), Web Graphics. Data stores with MSSQL Server, MySql Server, XML.
Love to "class"ify everything, make life easier by good strategy and coding.

My dev strategy is simple PPS - Presentation, Performance and Security.
Proudly Nigerian..

Comments and Discussions

 
QuestionExcelente aporte Pin
chavez_pepe1-Jul-21 17:53
chavez_pepe1-Jul-21 17:53 
Questionayuda Dismissable Pin
David Martinez27-Apr-17 7:38
David Martinez27-Apr-17 7:38 
QuestionDismissing the alert Pin
Member 1153001824-Apr-17 11:21
Member 1153001824-Apr-17 11:21 
QuestionWrong use of asp:Label control Pin
Member 74933925-Apr-16 1:38
Member 74933925-Apr-16 1:38 
AnswerRe: Wrong use of asp:Label control Pin
JoshYates198025-Aug-16 6:39
professionalJoshYates198025-Aug-16 6:39 
GeneralRe: Wrong use of asp:Label control Pin
Ovie Prince Tegaton6-Sep-16 21:45
professionalOvie Prince Tegaton6-Sep-16 21:45 
GeneralRe: Wrong use of asp:Label control Pin
JoshYates198023-Sep-16 3:17
professionalJoshYates198023-Sep-16 3:17 
unless you keep it simple, I don't recommend it. For example,

<asp:Label runat="server" Text="This has<br />a break." />


I included the BR tag in the string.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.