Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Equivalent of Page_Load

I have a session variable that is set in my MVC application. Whenever that session expires and the user tries to refresh the page that they're on, the page will throw an error because the session is not set anymore.

Is there anywhere I can check to see if the session is set before loading a view? Perhaps putting something inside the Global.asax file?

I could do something like this at the beginning of EVERY ActionResult.

public ActionResult ViewRecord()
{
    if (MyClass.SessionName == null)
    {
        return View("Home");
    }
    else
    {
        //do something with the session variable
    }
}

Is there any alternative to doing this? What would the best practice be in this case?

like image 466
Turp Avatar asked Apr 10 '12 14:04

Turp


1 Answers

If it's in one controller, you can do this:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    base.OnActionExecuting(filterContext);
    ... // do your magic
}   

It will fire before on any action execution. You can't return a view from there though, you'll have to redirect to anything that returns action result, e.g:

filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Shared" }, { "action", "Home" } });

But, obviously, that should redirect to the action in the controller that's not affected by the override, otherwise you have a circular redirect. :)

like image 108
Patryk Ćwiek Avatar answered Oct 23 '22 00:10

Patryk Ćwiek