Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use cached data on an action filter, to avoid another execution of an action

I would like to do the following (i will split in two points):

  • Before execution of the action, if the viewmodel is in cache then return the view and the viewmodel without execute the action.

  • If is not in the cache, continue with the execution of the action, and reach the OnActionExecuted to put the viewmodel in cache.

How could i return the view and the viewmodel without execute the action (first point)?

This is the code. My doubt indicated with ???????:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   //IF the viewmodel exists dont execute the action again
   if (filterContext.HttpContext.Cache["viewmodel"]!=null)
   {
      filterContext.Result=???????
   }
   base.OnActionExecuting(filterContext);
}

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    //Cast de model
    ContentDetailVM model = (ContentDetailVM)filterContext.Controller.ViewData.Model;
    filterContext.HttpContext.Cache.Insert("viewmodel", model);
    //we're asking for a close section
    if (model.CurrentSection.HideAccess == true)
    {
         //pass to the client some flag in order to show the div
         filterContext.Controller.ViewData["showoverlaylayer"]=true;
    }
    base.OnActionExecuted(filterContext);     
}

Thanks a lot in advance.

Best Regards.

Jose.

like image 706
Jose3d Avatar asked Jun 03 '11 08:06

Jose3d


1 Answers

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var model = filterContext.HttpContext.Cache["viewmodel"];
    if (model != null)
    {
        var result = new ViewResult();
        result.ViewData.Model = model;
        filterContext.Result = result;
    }
}
like image 154
Darin Dimitrov Avatar answered Sep 18 '22 12:09

Darin Dimitrov