Show Message on Redirect Without Using Session in ASP.Net MVC

In ASP.NET MVC, it may happen that you need to display a message to the user after a server is processing.
 
Out if a controller action redirects web, the message will be lost.
 
In most of my ASP.NET MVC projects I disable the session mechanism. Under these conditions, how to display a message to the user even if a redirect should take place?
 
So here is a simple solution to record a message to be consumed by the application as the user will display a page (View).
 
1. BaseController
 
It comes as a first step to create a BaseController that will inherit our controllers.
 
This controller will contain the notification to display to the user and a method to populate this property.
 
At the end of the action, if a notification exists, we store the notification in the ViewData to display it in a dedicated view:  
  1. public abstract partial class BaseController: Controller {  
  2.     private string notification;  
  3.     /// <summary>    
  4.     /// Add notification to users    
  5.     /// </summary>    
  6.     /// <param name="message"></param>    
  7.     protected void AddNotification(string message) {  
  8.         notification = message;  
  9.     }  
  10.     /// <summary>    
  11.     /// </summary>    
  12.     /// <param name="filterContext"></param>    
  13.     protected override void OnResultExecuting(ResultExecutingContext filterContext) {  
  14.         if (!string.IsNullOrWhiteSpace(this.notification)) filterContext.Controller.ViewData.Add("PageLoadNotification"this.notification);  
  15.     }  
  16. }  
Since your controllers, you can now add notifications:  
  1. public class HomeController: BaseController {  
  2.     public ActionResult Index() {  
  3.         AddNotification("hello");  
  4.         return View();  
  5.     }  
  6. }  
2. Notification.cshtml
 
We will now create a _notifications.cshtml view in the folder "Views\Shared", that will display notifications.
 
(Razor syntax) 
  1. @{    
  2.     var show = false;    
  3.     var notification = string.Empty;    
  4.         
  5.     if(ViewData.ContainsKey("PageLoadNotification"))    
  6.     {    
  7.         notication = ViewData["PageLoadNotification"] as string;    
  8.     }    
  9.     show = !string.IsNullOrWhiteSpace(notification);         
  10. }    
  11.     
  12.   
  13. <div @(Html.Raw(show ? "" : "style=\"display:none;\""))>    
  14.     @if (show)    
  15.     {    
  16.           
  17.     <text>    
  18.         @(notification)    
  19.         </text>    
  20.     }    
  21.   
  22. </div>  
In our View "master" we will add the view partial _notifications.cshtml:  
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <meta charset="utf-8" />  
  5.         <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  6.         <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  7.     </head>  
  8.     <body>  
  9.         <div class="page">    
  10.            @Html.Partial("_notifications")    
  11.            @RenderBody()    
  12.   
  13.            <div class="clear"></div>  
  14.        </div>  
  15.     </body>  
    </html>  
3. Redirects
 
The problem now is to manage a redirect. Imagine that an error occurs, or it redirects the user to another page wanting him to display the notification to the loading of the next page.
 
To do this, we will transit the message in a cookie that will be reset after having been consumed.
 
Here is a helper to manage your cookies easily: 
  1. public static class CookieManager {#region Get / Set  
  2.     /// <summary>    
  3.     /// Set a value in cookie in the response    
  4.     /// </summary>    
  5.     /// <param name="cookieName">Nom du cookie</param>    
  6.     /// <param name="value">Valeur</param>    
  7.     public static void SetValue(string cookieName, string value) {  
  8.         if (System.Web.HttpContext.Current != null) {  
  9.             HttpCookie c = new HttpCookie(cookieName, value);  
  10.             c.Expires = DateTime.Now.AddMonths(6);  
  11.             if (System.Web.HttpContext.Current.Response.Cookies.Get(cookieName) == null) System.Web.HttpContext.Current.Response.Cookies.Add(c);  
  12.             else System.Web.HttpContext.Current.Response.Cookies.Set(c);  
  13.         }  
  14.     }  
  15.     /// <summary>    
  16.     /// get a value from Request cookie    
  17.     /// </summary>    
  18.     /// <param name="cookieName">Nom du cookie</param>    
  19.     /// <returns>Valeur dans le cookie, chaine vide sinon</returns>    
  20.     public static string GetValue(string cookieName) {  
  21.         if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request.Cookies[cookieName] != nullreturn System.Web.HttpContext.Current.Request.Cookies[cookieName].Value;  
  22.         else return string.Empty;  
  23.     }#endregion  
  24. }  
Now, let's change our BaseController to store our notification in a cookie if redirected, or keep the current operation if a View is showing: 
  1. public abstract partial class BaseController: Controller {  
  2.     private string notification;  
  3.     protected override void OnResultExecuting(ResultExecutingContext filterContext) {  
  4.         if (filterContext.Result is ViewResult) {  
  5.             var notificationCookie = CookieManager.GetValue("wscNotification");  
  6.             if (!string.IsNullOrWhiteSpace(notificationCookie)) {  
  7.                 // There is an older notication :    
  8.                 this.notification = HttpUtility.UrlDecode(notificationCookie);  
  9.                 CookieManager.SetValue("wscNotification"string.Empty);  
  10.             }  
  11.             filterContext.Controller.ViewData.Add("PageLoadNotification"this.notification);  
  12.         } else {  
  13.             if (!string.IsNullOrWhiteSpace(this.notification)) {  
  14.                 // We store notication in cooki for the next request :    
  15.                 CookieManager.SetValue("wscNotification", HttpUtility.UrlEncode(this.notification));  
  16.             }  
  17.         }  
  18.     }  
  19. }  
Be careful
 
It is necessary to encode the data that you will store in your cookie for obvious security issues. Think to call methods HttpUtility.UrlEncode () and HttpUtility.UrlDecode () before storing the data in your cookie and vice versa. Could perfectly integrate these transformations into the CookieManager.
 
4. End
 
With this mechanism, you can now pass a message to your users from one page to another without going through the mechanism of the session!
 
Note that this always requires that your users accept cookies and you do not pass sensitive information, data that can be modified within the browser.

Up Next
    Ebook Download
    View all
    Learn
    View all