Skip to content

Instantly share code, notes, and snippets.

@mykeels
Last active January 28, 2021 19:22
Show Gist options
  • Save mykeels/59d1774b94248ded2dfe34daa45e8381 to your computer and use it in GitHub Desktop.
Save mykeels/59d1774b94248ded2dfe34daa45e8381 to your computer and use it in GitHub Desktop.
A notification system for ASP.NET MVC applications

AlertHandler

I'll go straight to the point ... sometimes, you have to notify a user of something on the following web page. What I used to do:

TempData["Notification"] = "You have succesfully logged in"; //c# code
@if (TempData["Notification"]) {
  <script>
    alert(TempData["Notification"]);
  </script>
}

The Problem

But this would mean that the the page that code is used on expects the notification.

What if it doesn't have to?

What if we can display notifications on any future page using a general system?

Perhaps such a scheme already it already exists; If so, kindly point me to it.

The Idea

I intend to build a notification system for ASP.NET MVC users that can accept notifications to be displayed on future pages.

Notification objects will be stored in TempData as usual, but this will just be wrapper around all that.

Code to add new notification

AlertHandler.AddNotification("User has logged in");

Code to render notifications in view (hopefully _Layout.cshtml)

Using the default notification template (which will be agreed on)

AlertHandler.RenderNotifications();

Using a custom notification template which takes in a Function argument that accepts a List of Notifications and returns a string which renders them according to the developer's preference.

@Html.Raw(AlertHandler.RenderNotifications((notifications) => {
  return "<script>" + 
        String.Join("\n", notifications.Select(notification => "alert('" + notification.Text + "');")) + 
        "</script>";
}));

Any Questions? 🙂

@mykeels
Copy link
Author

mykeels commented May 18, 2017

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace Notifications
{
    public class AlertHandler
    {
        private const string storageKey = "alert-notifications";
        private static HttpContext Context
        {
            get
            {
                return HttpContext.Current;
            }
        }

        private static HttpSessionState Session
        {
            get
            {
                return Context.Session;
            }
        }

        private static List<AlertNotification> Notifications
        {
            get
            {
                if (Session[storageKey] == null)
                {
                    Session[storageKey] = new List<AlertNotification>();
                }
                return (List<AlertNotification>)Session[storageKey];
            }
        }

        public static void AddNotification(AlertNotification notification)
        {
            Notifications.Add(notification);
        }

        public static string RenderNotifications()
        {
            string ret = "<script>\n" +
                            "$(document).ready(function () {\n" +
                            String.Join("\n", Notifications.Select(notification => "app.notifyMe({ message: '" + notification.Message + "', type: '" + notification.Type.ToString().ToLower() + "' });")) +
                            "});\n" +
                        "</script>";
            Notifications.Clear();
            return ret;
        }

        public static string RenderNotifications(Func<List<AlertNotification>, string> templateFn)
        {
            string ret = templateFn(Notifications);
            Notifications.Clear();
            return ret;
        }
    }

    public class AlertNotification
    {
        public string Message { get; set; }
        public NotificationType Type { get; set; }

        public enum NotificationType
        {
            Error,
            Success,
            Warning
        }

        public static AlertNotification Success(string message)
        {
            return new AlertNotification()
            {
                Type = NotificationType.Success,
                Message = message
            };
        }

        public static AlertNotification Warning(string message)
        {
            return new AlertNotification()
            {
                Type = NotificationType.Warning,
                Message = message
            };
        }

        public static AlertNotification Error(string message)
        {
            return new AlertNotification()
            {
                Type = NotificationType.Error,
                Message = message
            };
        }
    }
}

@mojoblanco
Copy link

I think it should be @AlertHandler.RenderNotifications() and not AlertHandler.RenderNotifications();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment