tobiak777
tobiak777

Reputation: 3365

How to clear Session after View Rendering

This initially looked like a game, but bit after bit I ended up carrying this issue for quite a long time. Here is my situation. I fire Notifications from my Domain Model.

These notifications are just objects containing a title and a description that I store in a collection in order to render them at the top of the pages of my website. However I'm having trouble to find the appropriate "session" mechanism with MVC.

I started by using HttpContext.Items to store all my session data, but I found out that it wasn't suitable for Redirection Scenarios - when I redirect the user to an other Action Method. Indeed a new HttpContext is created and the Items object is lost.

Consequently I tried storing my session stuff in HttpContext.Session but the issue I have now is that there is no appropriate time to clear the Session (I don't want to carry on the notifications from one request to the other). OnActionExecuted and OnResultExecuted seem to run before the View is Rendered.

Here is how I display the notifications in my Layout page :

@foreach(var notification in ISession.Notifications)
{
   @Html.Partial("_NotificationPartial", new Mvc.Models.NotificationViewModel(notification))
}

ISession is mapped to a store (HttpContext.Items / HttpContext.Session) in my IOC container.

Do you have any workaround idea ?

Upvotes: 0

Views: 508

Answers (1)

Mark Olsen
Mark Olsen

Reputation: 959

Try using the TempDataDictionary. It is included on the Controller base class as the TempData property. It is meant to persist data from one request to another. It is then cleared out automatically.

In the action method:

TempData["Notifications"] = new List<Notification>()

In the view:

@{
    if(TempData["Notifications"] != null)
    {
        var notifications = TempData["Notifications"] as List<Notification>
    }
}

Upvotes: 1

Related Questions