Click here to Skip to main content
13,860,742 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

23.8K views
1.1K downloads
31 bookmarked
Posted 14 Oct 2016
Licenced CPOL

Toastr.Net – Yet Another Notification Plugin Extender for ASP.NET

, 1 Apr 2018
Rate this:
Please Sign up or sign in to vote.
This is an implementation of John Papa’s Toastr plugin extended in ASP.NET server-side for a neater presentation of notifications.

Introduction

Toasts on webpage

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:

  • Typesuccess, info, warning, error
  • Message – The content to be displayed
  • Title – The title of the message to be displayed
  • Positiontop-right, top-left, top-center, bottom-right, bottom-left, bottom-center, top-full, bottom-full
  • Close ButtonTrue/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().

//------------TOASTR-------------//

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;
    }
    //toastr.clear();
}

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] 'Reserved word so we use []
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

        'Set the position based on selected and change value to match toastr plug in
        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

    'Call the toastify() function in script.js
        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
        'This function replaces ' with its html code equivalent
        'in order not to terminate the js statement string
        Return Text.Replace("'", "&#39;")
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.

Web page design

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.

License

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

Share

About the Author

Ovie Prince Tegaton
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..

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ehsan Sajjad4-Jul-17 6:13
mvpEhsan Sajjad4-Jul-17 6:13 
Questionzip file is damaged Pin
arman bay18-Jun-17 10:14
memberarman bay18-Jun-17 10:14 
AnswerRe: zip file is damaged Pin
Ovie Prince Tegaton4-Jul-17 3:35
professionalOvie Prince Tegaton4-Jul-17 3:35 
QuestionNice Share Pin
M,AqibShehzad17-Oct-16 22:10
professionalM,AqibShehzad17-Oct-16 22:10 
AnswerRe: Nice Share Pin
Ovie Prince Tegaton22-Oct-16 22:01
professionalOvie Prince Tegaton22-Oct-16 22:01 
GeneralRe: Nice Share Pin
M,AqibShehzad24-Oct-16 20:44
professionalM,AqibShehzad24-Oct-16 20:44 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190214.1 | Last Updated 2 Apr 2018
Article Copyright 2016 by Ovie Prince Tegaton
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid