【问题标题】:Use cached data on an action filter, to avoid another execution of an action在操作过滤器上使用缓存数据,以避免再次执行操作
【发布时间】:2011-06-03 08:51:40
【问题描述】:

我想做以下事情(我会分成两点):

  • 在执行操作之前,如果视图模型在缓存中,则返回视图和视图模型而不执行操作。

  • 如果不在缓存中,则继续执行动作,到达 OnActionExecuted 将视图模型放入缓存中。

如何在不执行操作(第一点)的情况下返回视图和视图模型?

这是代码。我的疑问用?????????表示:

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

非常感谢。

最好的问候。

何塞。

【问题讨论】:

    标签: asp.net-mvc action-filter


    【解决方案1】:
    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;
        }
    }
    

    【讨论】:

    • 一个问题,我得到错误原因是我使用母版页。你知道我是否需要为我创建的 ViewResult 分配更多属性吗?非常感谢。
    • 显然问题更复杂...问题是此操作过滤器适用于其他页面内的一个“小部件”(使用渲染操作),并且此页面是主页面。我想我不仅需要设置母版,还需要设置包含此小部件的页面等...谢谢
    • @Jose3d,是的,它更复杂 :-) 顺便问一下,您是否考虑过使用 [OutputCache] 属性?
    • 嗨达林,[OutputCache] 在我的情况下是不够的,“小部件视图”也会根据模型属性和一些安全性内容而变化。无论如何,我解决了它,稍微改变了你给我的代码,只需执行“var result = new PartialViewResult()”,它就可以工作了。感谢所有伟大的提示!
    • @DarinDimitrov 你好,达林,我在 ACtionFilterAttribute 内部做了很多调用。我可以将它们缓存在 asp.net 中吗
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多