Jose3d
Jose3d

Reputation: 9277

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):

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.

Upvotes: 6

Views: 2089

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038790

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;
    }
}

Upvotes: 7

Related Questions