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? 🙂

@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