Use Toast Notification popups in asp.net
jQuery has some wonderful toast notification popups. In some of my web projects they are really helpful, but I did not find an easy general solution how to add them into all of my asp.net pages. Sure there are commercial solutions e.g. from Telerik but as long as you don’t need the other included stuff they are oversized (and expensive) if you just need the toast notifications. So I tried to find a solution which is
- easy to implement,
- works fine with master pages and
- free of charge.
Choose the Javascript plugin to use
So first I had a look at the existing Toast Popups to find the one I want to use. jQuery has some, Github has some more. I’ve checked some of them, and in the end I decided to use Toastr. Of course it’s entirely up to you. The described solution should be easy to adjust for your favorite kind of toast popup if you prefer another one.
jQuery Toastr
Toastr is created by Hans Fjällemark, John Papa and Tim Ferrell.It’s available on Github under MIT license, so you could use the script wherever you want. It is easy to implement, especially with Masterpages.
Include the files
If you do not have a Webapplication yet, please create one including a masterpage. The necessary Toastr-Files are available on CDN JS so you could download them from Github or include them from their Content Delivery Network. You need to include a Javascript-File toastr.min.js
and a CSS file toastr.min.css. Just add them to the Header of your Masterpage. Of course make sure to reference jQuery before toastr.min.js. Complete Source code from example is available below.
Create new vb.net class for Toastr
As I want to implement the Toast easily into any of my projects I’ve created a new class ‘toastr’ for it (see toastr.vb below). Toastr has a lot of options as you can see in their demo but for me the default is fine for most options. So I decided to support only these options:
- Title
- Text
- Type (info, success, warning, error)
- Position (upper-right etc.)
If you want to be able to modify also some other available options feel free to add these options to toastr.vb according to your needs. I’ve also decided that I do not need to support displaying multiple toasts at the same time.
Where to keep the toast
The toast might not always be displayed on the current page. One common scenario is that the user fills out a form, saves it, and is then automatically forwarded to an overview page. So the toast should appear when the overview page opens. Therefore it’s necessary to store the toast details in a session value. I’m using ‘toastr’ as session name, feel free to change if you already use this session name for whatever reasons.
How to create new instance of toastr
I’ve added several overloads to the creation of a new instance. In many cases it’s fine to just supply the text to be displayed. The toast will then be shown by default as info-box in the upper right. The other overloads support supplying a title, a position and / or a different type. Additionally I have a create a shared sub ‘SetToast’ with the same overloads. So you could add a new toast without the need of manually initiating a new instance of class toastr. You could use the way you prefer. As you see, SetToast will initiate a new instance and then store it in the session.
Later on we also need to be able to access the supplied attributes like text, title, type and position so the corresponding readonly properties are also added to the class. And if you wonder: Enumerations are not allowed to contain hyphens so I’m using underscores which are then replaced within the property for use in the jQuery plugin.
Create new toast
To create a new toast I’ve added a button to my website Toast.aspx. It just contains 2 records: First it creates a new toast showing current time, then it redirects the user to Page2. So normally on button click you have some processing in the backend, e.g. write user data into your database. If all went fine you create a toastr saying ‘Your new data is stored successfully’ and redirect the user to his overview page or else.
toastr.SetToast(Now.ToString("F")) Response.Redirect("Toast2.aspx")
Show toasts
Instead of adding the processing onto every aspx-page where the toast might appear (Toast.aspx, Toast2.aspx, etc.) I’ve added the processing to the master page. So I only need to add it once and it’s observed on all pages! The following JavaScript needs to be added to the end of your MasterPage-Body:
<script type="text/javascript"> $(function () { var toast = '<%=toastrText %>'; // Check whether a toast should be displayed if (toast) { var toasttype = '<%=toastrType %>'; var toastposition = '<%=toastrPosition %>'; toastr.options = { "positionClass": toastposition } toastr[toasttype](toast); } }) </script>
It checks whether a toast should be displayed. If so, it retrieves the necessary options and displays the toast as requested. Of course we also need some code in the Masterpage vb. We only need to define a private toastr instance and retrieve it on page load. Of course we also need the public readonly properties which are retrieved by the above listed JavaScript.
That’s it!
So that’s it. You could now use the Toast Notification popups on every page withinyour webapplication. No need to modify anything on your single pages.
tl;dr
To use toastr in asp.net pages you need to
- Include jQuery, toastr.min.css and toastr.min.js
- Include toastr.vb
- Add some public properties and a Javascript to your masterpage
- Create a new toast with a single line of code wherever your want
The code
Site1.Master
<%@ Master Language="VB" AutoEventWireup="false" CodeBehind="Site1.master.vb" Inherits="WebApplication1.Site1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet" /> <script src="//code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js" type="text/javascript"></script> <asp:ContentPlaceHolder ID="head" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <div> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> <script type="text/javascript"> $(function () { var toast = '<%=toastrText %>'; // Check whether a toast should be displayed if (toast) { var toasttype = '<%=toastrType %>'; var toastposition = '<%=toastrPosition %>'; toastr.options = { "positionClass": toastposition } toastr[toasttype](toast); } }) </script> </form> </body> </html>
Site1.Master.vb
Public Class Site1 Inherits System.Web.UI.MasterPage Private currentToastr As toastr Public ReadOnly Property toastrTitle As String Get If currentToastr Is Nothing Then Return String.Empty Else Return currentToastr.toastTitle End Get End Property Public ReadOnly Property toastrText As String Get If currentToastr Is Nothing Then Return String.Empty Else Return currentToastr.toastText End Get End Property Public ReadOnly Property toastrType As String Get If currentToastr Is Nothing Then Return String.Empty Else Return currentToastr.toastType End Get End Property Public ReadOnly Property toastrPosition As String Get If currentToastr Is Nothing Then Return String.Empty Else Return currentToastr.toastPosition End Get End Property Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load SetToast() End Sub Public Sub SetToast() currentToastr = toastr.GetToast End Sub End Class
Toast.aspx
<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site1.Master" CodeBehind="Toast.aspx.vb" Inherits="WebApplication1.Toastr1" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <asp:Button ID="ShowTime" Text="Show current time in info toast" runat="server" /> </asp:Content>
Toast.aspx.vb
Public Class Toastr1 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load End Sub Private Sub ShowTime_Click(sender As Object, e As System.EventArgs) Handles ShowTime.Click toastr.SetToast(Now.ToString("F")) Response.Redirect("Toast2.aspx") End Sub End Class
Toast2.aspx
<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site1.Master" CodeBehind="Toast2.aspx.vb" Inherits="WebApplication1.Toast2" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <asp:Button ID="BackToPage1" Text="Go back to Page 1 without any toast" runat="server" /> <asp:Button ID="BackToPage1WithToast" Text="Go back to Page 1 with toast" runat="server" /> </asp:Content>
Toast2.aspx.vb
Public Class Toast2 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load End Sub Private Sub BackToPage1_Click(sender As Object, e As System.EventArgs) Handles BackToPage1.Click Response.Redirect("Toast.aspx") End Sub Private Sub BackToPage1WithToast_Click(sender As Object, e As System.EventArgs) Handles BackToPage1WithToast.Click toastr.SetToast("Action completed successfully", toastr.ToastTypes.success, toastr.ToastPositions.toast_top_full_width) Response.Redirect("Toast.aspx") End Sub End Class
toastr.vb
''' <summary> ''' Using Toastr from CodeSeven https://github.com/CodeSeven/toastr ''' </summary> ''' <remarks></remarks> Friend Class toastr Friend Const SessionName As String = "toastr" Private t_Title As String Private t_Text As String Private t_Type As ToastTypes Private t_Position As ToastPositions Friend Enum ToastTypes info success warning [error] End Enum Friend Enum ToastPositions toast_top_right toast_bottom_right toast_bottom_left toast_top_left toast_top_full_width toast_bottom_full_width toast_top_center toast_bottom_center End Enum ''' <summary> ''' Show info toast at top right ''' </summary> ''' <param name="text">Text to be shown in the toast</param> ''' <remarks></remarks> Friend Sub New(text As String) t_Text = text t_Title = String.Empty t_Type = ToastTypes.info t_Position = ToastPositions.toast_top_right End Sub ''' <summary> ''' Show toast at top right ''' </summary> ''' <param name="text">Text to be shown in the toast</param> ''' <param name="type">Type of Toast. Could be info, success, warning or errors.</param> ''' <remarks></remarks> Friend Sub New(text As String, type As ToastTypes) t_Text = text t_Type = type.ToString t_Title = String.Empty t_Position = ToastPositions.toast_top_right End Sub ''' <summary> ''' Show info toast ''' </summary> ''' <param name="text">Text to be shown in the toast</param> ''' <param name="position">Position of Toast. Several options available</param> ''' <remarks></remarks> Friend Sub New(text As String, position As ToastPositions) t_Text = text t_Type = ToastTypes.info t_Title = String.Empty t_Position = position End Sub ''' <summary> ''' Show toast ''' </summary> ''' <param name="text">Text to be shown in the toast</param> ''' <param name="type">Type of Toast. Could be info, success, warning or errors.</param> ''' <param name="position">Position of Toast. Several options available</param> ''' <remarks></remarks> Friend Sub New(text As String, type As ToastTypes, position As ToastPositions) t_Text = text t_Type = type t_Position = position t_Title = String.Empty End Sub Friend ReadOnly Property toastTitle As String Get Return t_Title End Get End Property Friend ReadOnly Property toastText As String Get Return t_Text End Get End Property Friend ReadOnly Property toastType As String Get Return t_Type.ToString End Get End Property Friend ReadOnly Property toastPosition As String Get Return t_Position.ToString.Replace("_", "-") End Get End Property ''' <summary> ''' Retrieve Toast from Session and remove Sessionvalue afterwards ''' </summary> ''' <returns>Toast to be displayed</returns> ''' <remarks></remarks> Friend Shared Function GetToast() As toastr If Not System.Web.HttpContext.Current.Session(SessionName) Is Nothing Then GetToast = CType(System.Web.HttpContext.Current.Session(SessionName), toastr) System.Web.HttpContext.Current.Session.Remove(SessionName) Else GetToast = Nothing End If End Function ''' <summary> ''' Store new toast in user session ''' </summary> ''' <remarks></remarks> Friend Overloads Shared Sub SetToast(toast As toastr) System.Web.HttpContext.Current.Session(SessionName) = toast End Sub ''' <summary> ''' Store new info toast in user session to be shown in upper right ''' </summary> ''' <param name="text">Text to be shown in the toast</param> ''' <remarks></remarks> Friend Overloads Shared Sub SetToast(text As String) System.Web.HttpContext.Current.Session(SessionName) = New toastr(text) End Sub ''' <summary> ''' Store new toast in user session to be shown in upper right ''' </summary> ''' <param name="text">Text to be shown in the toast</param> ''' <param name="type">Type of Toast. Could be info, success, warning or errors.</param> ''' <remarks></remarks> Friend Overloads Shared Sub SetToast(text As String, type As ToastTypes) System.Web.HttpContext.Current.Session(SessionName) = New toastr(text, type) End Sub ''' <summary> ''' Store new info toast in user session ''' </summary> ''' <param name="text">Text to be shown in the toast</param> ''' <param name="position">Position of Toast. Several options available</param> ''' <remarks></remarks> Friend Overloads Shared Sub SetToast(text As String, position As ToastPositions) System.Web.HttpContext.Current.Session(SessionName) = New toastr(Text, position) End Sub ''' <summary> ''' Store new toast in user session ''' </summary> ''' <param name="text">Text to be shown in the toast</param> ''' <param name="type">Type of Toast. Could be info, success, warning or errors.</param> ''' <param name="position">Position of Toast. Several options available</param> ''' <remarks></remarks> Friend Overloads Shared Sub SetToast(text As String, type As ToastTypes, position As ToastPositions) System.Web.HttpContext.Current.Session(SessionName) = New toastr(text, type, position) End Sub End Class
Hi,
How can I use it OnClick event of a button and without redirect / refresh page?
Thanks
Sorry, too long ago…
how can i add the title and close button in this toastr
Just add a new “Friend Sub New” with additional option title and close button boolean. I’ve never used a close button (as it’s a toast, not a popup) but according to https://codeseven.github.io/toastr/demo.html there is an option which you could supply.