Introduction
It seems I am very obsessed about notifications in ASP.NET given that I extended Bootstrap Alert already from server-side in a CodeProject article a while ago, now it’s time to move on with John Papa’s Toastr jQuery based notification. This is a smooth way to display messages to clients from webpages, now the task here has been simplified using this Toastr plug in which I now call Toastr.Net, especially built for ASP.NET apps.
Background
Like I said earlier, I am not the originator of this plug in, all I am doing here is to extend it for easier implementation in ASP.NET web apps.
I have stumbled upon some articles on this same subject but none has been easy to implement for me, maybe lack of proper explanation on how the process works or improper breakdown of the entire process. It made me dump the idea of using Toastr in some of my past projects but of late, I found a sweet formula to unlock the beauty in it for ASP.NET apps and now it’s time to share it with you all. Who knows, it may come in handy for you sooner.
Checkout the Toastr plug in by John Papa here or on github.
Using the Code
By now, I hope you have enough knowledge of the Toastr JavaScript plug in from the links above, but for the sake of understanding, we will go through the basics.
What Does Toastr Provide For You
toastr
function accepts these basic parameters:
Type
– success, info, warning, error
Message
– The content to be displayed Title
– The title of the message to be displayed Position
– top-right, top-left, top-center, bottom-right, bottom-left, bottom-center, top-full, bottom-full
Close Button
– True
/False
if the user can close the message by clicking a close (x) icon
While initializing the function, you can set the following options:
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-top-right",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
Toastr.Net
Step 1: The Dependencies
First, we call toastr.min.css, jQuery, toastr.min.js, and script.js.
<link href="Assets/toastr.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery.js"></script>
<script src="Assets/toastr.min.js"></script>
<script src="Assets/script.js"></script>
For us to use this plug in in ASP.NET projects, I have utilized the Toastr
function in an external JavaScript file which can be renamed or copied into your general script file, but for now, let's call it script.js with a function I created as toastify()
.
function toastify(type, msg, title, position, showclosebutton) {
if (position == null || position == '') {
toastr.options.positionClass = 'toast-bottom-right';
}
else {
toastr.options.positionClass = position;
}
if (showclosebutton == null || showclosebutton == '' || showclosebutton == 'true') {
toastr.options.closeButton = 'true';
}
toastr.options.timeOut = '50000';
toastr.options.progressBar = true;
switch (type) {
case 'success': toastr.success(msg, title);
break;
case 'info': toastr.info(msg, title);
break;
case 'warning': toastr.warning(msg, title);
break;
case 'error': toastr.error(msg, title);
break;
}
}
Step 2: Toastr Class (VB.NET)
The Toastr.vb class is located in the App_Code folder for reusability. Let’s talk about the pieces of code that makes it toast. In order to be precise when using the message types, instead of passing it as string
every time, it’s available as Enumeration. Remember, JavaScript is case sensitive.
Public Enum ToastType
Success
Info
Warning
[Error]
End Enum
Same for the toast positions:
Public Enum ToastPosition
TopRight
TopLeft
TopCenter
TopStretch
BottomRight
BottomLeft
BottomCenter
BottomStretch
End Enum
ShowToast Function
Public Shared Sub ShowToast(Page As Page, Type As ToastType, Msg As String, _
Optional Title As String = "", Optional Position As ToastPosition = ToastPosition.BottomRight,
Optional ShowCloseButton As Boolean = True)
Dim strType = "", strPosition = ""
Select Case Type
Case ToastType.Success
strType = "success"
Case ToastType.Info
strType = "info"
Case ToastType.Warning
strType = "warning"
Case ToastType.Error
strType = "error"
End Select
Select Case Position
Case ToastPosition.TopRight
strPosition = "toast-top-right"
Case ToastPosition.TopLeft
strPosition = "toast-top-left"
Case ToastPosition.TopCenter
strPosition = "toast-top-center"
Case ToastPosition.TopStretch
strPosition = "toast-top-full-width"
Case ToastPosition.BottomRight
strPosition = "toast-bottom-right"
Case ToastPosition.BottomLeft
strPosition = "toast-bottom-left"
Case ToastPosition.BottomCenter
strPosition = "toast-bottom-center"
Case ToastPosition.BottomStretch
strPosition = "toast-bottom-full-width"
End Select
Dim script = "toastify('" & strType & "', '" & CleanStr(Msg) & "', _
'" & CleanStr(Title) & "', '" & _
strPosition & "', '" & ShowCloseButton & "');"
Page.ClientScript.RegisterStartupScript(Page.GetType(), "toastedMsg", script, True)
End Sub
Private Shared Function CleanStr(Text As String) As String
Return Text.Replace("'", "'")
End Function
Live Scenario
As seen in the sample attached to this article, following all steps shown, add a standalone WebForm or with a MasterPage.
Add the following HTML code to the page.
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Toastr.Net - Display beautiful notifications</h3>
</div>
<div class="panel-body">
<p>Select an option</p>
<p>
<asp:RadioButtonList ID="rdoOptions" runat="server">
<asp:ListItem Selected="True">Success message</asp:ListItem>
<asp:ListItem>Information message</asp:ListItem>
<asp:ListItem>Warning message</asp:ListItem>
<asp:ListItem>Error message</asp:ListItem>
</asp:RadioButtonList>
</p>
<p>
<asp:Button ID="btnShow" runat="server" Text="Toastify"
Font-Bold="true" CssClass="btn btn-primary" />
</p>
</div>
From CodeBehind, call the Toastr
function and pass all necessary parameters.
Protected Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Select Case rdoOptions.SelectedIndex
Case 0 : Toastr.ShowToast(Me, ToastType.Success, _
"Congrats! You have been won a cash sum of $5k", "Winner!")
Case 1 : Toastr.ShowToast(Me, ToastType.Info, _
"You will have to wait for 5 working days before you'll be credited", _
"Notice", ToastPosition.TopRight)
Case 2 : Toastr.ShowToast(Me, ToastType.Warning, _
"Please keep this a secret, you may be kidnapped!", _
"Warning!", ToastPosition.BottomLeft)
Case 3 : Toastr.ShowToast(Me, ToastType.Error, _
"There is nothing like a free $5k, it was just a joke..", "Oops!")
End Select
End Sub
What You Should Know
The icons used are base-64 images which can be seen in the toastr.min.css, you may choose to change it to svg icons or live images if you wish but I love it this way. Just a notice.
Configure for Easy Accessibility
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 your project scope.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 your project scope.
<configuration>
<system.web>
<compilation debug="true" strict="false" />
<httpRuntime targetFramework="4.5" />
<pages>
<namespaces>
<add namespace="Toastr" />
</namespaces>
</pages>
</system.web>
</configuration>
Or do this in the WebForm class level.
Imports Toastr
Partial Class _Default
Inherits System.Web.UI.Page
End Class
Point of Interest
This article and piece of extension succeeds my BootstrapAlert article I posted here on CodeProject. My web app is always streamlined to what I tag as PPS (Presentation, Performance and Security), on presentation level I think this is a very handy extension for any web app.