【问题标题】:Whats the recommended way to cache 'expensive' queries in an MVC HTML Helper?在 MVC HTML Helper 中缓存“昂贵”查询的推荐方法是什么?
【发布时间】:2012-09-24 15:53:43
【问题描述】:

我正在尝试在 HTML Helper 上使用输出缓存。但是,即使设置了属性,在调用 Helper 方法时始终会输入此代码块。由于 outputcache 属性在这种情况下不起作用,在 Html Helpers 中缓存“昂贵”查询的推荐方法是什么?

     [OutputCache(Duration = 60)]
     public static MvcHtmlString CountryDropDownListFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object selectedValue)
    {
        var doc = new XmlDocument();
        doc.Load(HttpContext.Current.Server.MapPath("~/App_Data/countries.xml"));

        var items = new Dictionary<string, string>();

        foreach (XmlNode node in doc.SelectNodes("//country"))
        {
            items.Add(node.InnerText, node.InnerText);
        }

        return html.DropDownListFor(expression, new SelectList(items, "key", "value", selectedValue));
    }

【问题讨论】:

    标签: model-view-controller html-helper outputcache


    【解决方案1】:

    输出缓存允许您将操作方法​​的输出存储在 Web 服务器的内存中。例如,如果 action 方法渲染一个视图,该视图页面将被缓存。然后,此缓存页面可供应用程序用于后续请求。输出缓存为您的应用程序节省了重新创建操作方法结果所需的时间和资源。

    在 ASP.NET MVC 中,您可以使用 OutputCacheAttribute 属性来标记要缓存其输出的操作方法。如果使用 OutputCacheAttribute 属性标记控制器,则控制器中所有操作方法的输出都会被缓存。

    详情http://msdn.microsoft.com/en-us/library/system.web.mvc.outputcacheattribute(v=vs.108).aspx

    您将此属性用于不采取行动的方法

    正确的例子

    [OutputCache(Duration = 50000)]
    public ActionResult CountryDropDownListFor()
    {
       // Code 
    }
    

    在你看来,你可以使用 Html.PartialAction 来渲染一个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 2012-08-12
      • 2017-12-23
      相关资源
      最近更新 更多