Simple MVC 3 Notifications (with Razor and jQuery)

Author: Eric G. |  Views: 7,976

This needs to be said first: I am brand new to ASP.NET MVC 3.  Before about 2 or 3 weeks ago, I didn’t really care about MVC, nor did I have any real desire to learn it.  What changed my mind was the work group I work in, and the unwillingness some people in that group have to learn new things.  I didn’t want to get left behind, so I decided to choose something that was gaining a lot of support, both from developers and Microsoft as well, and that was MVC.  Now, with that said, keep in mind I’ve only been coding MVC for about 2 weeks max.  The issue that I ran into last night, was I wanted to display a simple notification to the user when they updated their support ticket in the ticketing application I’m working on.  I found 3 very different implementations of a notification system last night, but felt that they were a little too complex for what I wanted to do.  The outcome of my research last night led me to building an extremely simplified combination of all 3 implementations.  For reference, the 3 implementations I found are:

http://blogs.planetcloud.co.uk/mygreatdiscovery/post/Using-TempData-to-display-notifications.aspx (Ben)

http://www.digitaltoolfactory.net/blog/2011/05/how-to-do-a-cool-flash-notification-message-in-asp-net-mvc-3-in-6-easy-steps/

http://blogs.taiga.nl/martijn/2011/05/03/keep-your-users-informed-with-asp-net-mvc/ (Martijn)

I used the simplified display from Ben’s example, the jQuery from Digital Tool Factory’s example and the look and feel from Martijn’s example.  This allowed me to basically have my own implementation of the notification system that did exactly what I wanted and looked the way I want.  The end result looks like this:



Alright.  Now that that’s out of the way, let’s get to the code.  Start off by adding the following jQuery code to your _Layout.cshtml file (make sure you have imported the jQuery libraries for this to work and feel free to adjust the fadein, fadeout and delay times as you see fit):

<script language="javascript" type="text/javascript">
     $(document).ready(function () {
          $("#NotificationBox").fadeIn(5000);

          if ($("#NotificationBox").attr('class').split(' ').slice(-1) == "nb-success") {
               $("#NotificationBox").delay(3000).fadeOut(1000);
          }
     });
</script>

After you’ve added the jQuery code to your _Layout.cshtml file, determine where you would like the notification to be displayed at. Mine is also in the _Layout.cshtml file. Just copy and paste this where you want it to go:

@if (TempData["Notification"] != null)
{
     <div id="NotificationBox" class="@TempData["NotificationCSS"]" style="display: none">
          @TempData["Notification"]
     </div>
}

Now add the following the CSS classes to your Site.css file (You can download the images here and make sure they’re in Content\images):

/* Notification styles
-----------------------------------------------------------*/
.notificationbox
{
z-index: 1000;
padding: 12px 10px 10px 30px;
margin-top: 10px;
	box-shadow: 5px 5px 10px #000;
	display: none;
	width: 550px;
}

.nb-success
{
color: #060;
	background: #cfc url(images/ok.gif) no-repeat 8px 12px;
}

.nb-error
{
color: #c00;
	background: #fcc url(images/fail.gif) no-repeat 8px 12px;
}

.nb-warning
{
color: #c60;
	background: #ffc url(images/warn.gif) no-repeat 8px 12px;
}

Now that you have everything set for displaying the notification, it’s time to actually show something. My use was very specific for the notifications (which is why I have the colors in the CSS split up the way I do). I also wanted to make sure that on errors and warnings, the notification did not fade out, and stayed visible for the user, so using two CSS classes was the simple solution for me. This notification system makes use of of the TempData property in MVC. TempData is a dictionary of key/value pairs that temporarily stores a value during a single Http Request (unless marked for retention), so that you can easily pass something an update message back to the view. You can read more on using TempData on MSDN. Now, to display a notification to the user, in your controller classes, just add the following code before you return your view or do a RedirectToAction():

this.TempData["Notification"] = "Your support ticket was created successfully.";
this.TempData["NotificationCSS"] = "notificationbox nb-success";

//To display an error use
this.TempData["NotificationCSS"] = "notificationbox nb-error";

//To display a warning use
this.TempData["NotificationCSS"] = "notificationbox nb-warning";

This is all that’s needed to display a simple notification using MVC 3 and jQuery. This should provide a very simple solution without the need to write extension methods on your controllers. However, keep in mind that this has only been tested on a single controller, and may or may not work across multiple controllers. I hope this helps anyone that’s been looking for a simple and straightforward way to do this.

Update: After I posted this earlier, I decided to go back and look at it to see if there was anyway I could improve this, while still keeping it simple.  I wanted to keep this implementation as simple as possible, but also make it a little more flexible as well.  My solution to this was to create a base controller class that all of my other controllers would inherit from which would set the values that I needed.  I also added an enumeration (which was mentioned in Martijn’s implementation as well).  There were were a couple changes made to the jQuery code to allow for this, and one change made to the layout in _Layout.cshtml.  The code changes are below:

Enumeration

public enum NotificationEnumeration
{
    Success,
    Error,
    Warning
}

jQuery Code

<script language="javascript" type="text/javascript">
     //Used to display and close the system notifications
     $(document).ready(function () {
	$("#NotificationBox").fadeIn(1000);

	if ($("#NotificationAutoHide").val() == "true") {
            //$("#NotificationBox").delay(3000).fadeOut(2000);
	    $("#NotificationBox").delay(5000).slideUp(1000);
	}
    });
</script>

Layout Changes (in _Layout.cshtml)

@if (TempData["Notification"] != null)
{
    @Html.Hidden("NotificationAutoHide", TempData["NotificationAutoHide"])
    <div id="NotificationBox" class="@TempData["NotificationCSS"]" style="display: none">
        @TempData["Notification"]
    </div>
}

Base Controller Class

public abstract class BaseController : Controller
{
    /// <summary>
    /// Sets the information for the system notification.
    /// </summary>
    /// <param name="message">The message to display to the user.</param>
    /// <param name="autoHideNotification">Determines whether the notification will stay visible or auto-hide.</param>
    /// <param name="notifyType">The type of notification to display to the user: Success, Error or Warning.</param>
    public void SetNotification(string message, NotificationEnumeration notifyType, bool autoHideNotification = true)
    {
        this.TempData["Notification"] = message;
        this.TempData["NotificationAutoHide"] = (autoHideNotification) ? "true" : "false";

        switch (notifyType)
        {
            case NotificationEnumeration.Success:
                this.TempData["NotificationCSS"] = "notificationbox nb-success";
                break;
            case NotificationEnumeration.Error:
                this.TempData["NotificationCSS"] = "notificationbox nb-error";
                break;
            case NotificationEnumeration.Warning:
                this.TempData["NotificationCSS"] = "notificationbox nb-warning";
                break;
        }
    }
}

Usage (Make sure your Controller inherits from your BaseController class instead of Controller)

//Set the Notification and NotificationCSS properties
this.SetNotification("Your support ticket was created successfully.", NotificationEnumeration.Success);

//Or, to keep the notification visible instead of auto-hiding
this.SetNotification("There was an error updating this ticket.", NotificationEnumeration.Error, false);

I tried to keep this as simple as possible, while adding a little more flexibility to the implementation. I hope this helps anyone looking for a simple solution to making a notification system.

Tags: , , , ,

  • Bhopal Saini

    Hi Eric Garrison,

    Thanks a lot for this, its helpful for me, could you please help me, if i want to show this notification on Ajax call means for client side validation

    Rate Comment: Thumb up 0 Thumb down 0

  • http://www.facebook.com/eric.d.garrison Eric Garrison

    What exactly do you need help with on this? If you want to use this asynchronously, you may have to use a partial view instead. I wrote this when I first started learning MVC, so just about everything was done using HttpPosts and HttpGets. If you want to use it for an Ajax call, then you can put the notification in a partial view, then use jQuery to load that partial view.

    Rate Comment: Thumb up 0 Thumb down 0

  • Ashhar Hasan

    Thank you sir you saved my day

    Rate Comment: Thumb up 0 Thumb down 0