我正在使用CachedPartial html帮助程序来缓存该部分视图。
@Html.CachedPartial("PartialView", MyModel, 3600, true);
在我看来,我有以下情况:
@Html.CachedPartial("PartialView", MyModel, 3600, true);
@Html.CachedPartial("AnotherPartialView", MyModel1, 3600, true);
@Html.CachedPartial("PartialView", MyModel3, 3600, true); // I want to reuse partial view
由于CachedPartial
...
如何通过模型参数进行缓存局部化?
我尝试使用
@Html.CachedPartial("PartialView", MyModel, 3600, true, false, new ViewDataDictionary(MyModel3));
但同样的事情。
编辑:我使用了与DZL不同的方法,它可以正常工作
public static IHtmlString CachedPartial( this HtmlHelper helper, string partialViewName, object model, string cacheKey = null )
{
if ( string.IsNullOrWhiteSpace( cacheKey ) ) {
return helper.CachedPartial( partialViewName, model, AppSettings.PartialCachingSeconds, true );
}
Func<object, ViewDataDictionary, string> fc = ( o, v ) => cacheKey;
return helper.CachedPartial( partialViewName, model, AppSettings.PartialCachingSeconds, true, contextualKeyBuilder: fc );
}
然后
@Html.CachedPartial("PartialView", MyModel, "a_key");
@Html.CachedPartial("AnotherPartialView", MyModel1);
@Html.CachedPartial("PartialView", MyModel3, "another_key"); // I want to reuse partial view
答案 0 :(得分:3)
如果您需要,您需要创建自己的using System;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Umbraco.Web;
using System.Web;
using System.Runtime.Caching;
public static class CachedPartialExtensions
{
public static IHtmlString MyCachedPartial(
this HtmlHelper htmlHelper,
string partialViewName,
object model,
int cachedSeconds,
bool cacheByPage = false,
string cacheKey = null,
ViewDataDictionary viewData = null
)
{
var newCacheKey = "fpc-"; //prefix to know which keys to clear on page publish (in Bootstraper.cs file)
newCacheKey += partialViewName;
if (cacheByPage)
{
newCacheKey += "page-" + UmbracoContext.Current.PageId;
}
if (!string.IsNullOrEmpty(cacheKey))
{
newCacheKey += "key-" + cacheKey;
}
var result = MemoryCache.Default.Get(newCacheKey) as MvcHtmlString;
if(result == null)
{
result = htmlHelper.Partial(partialViewName, model, viewData);
MemoryCache.Default.Add(new CacheItem(newCacheKey, result), new CacheItemPolicy
{
AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(cachedSeconds)
});
}
return result;
}
}
实现,如下所示:
@Html.MyCachedPartial("PartialView", Model, 60, cacheKey: "model1key", cacheByPage: true)
@Html.MyCachedPartial("PartialView", Model2, 60, cacheKey: "model2key", cacheByPage: true)
然后您将能够提供自己的缓存密钥:
CachedPartial
编辑:
从版本7开始,public static IHtmlString CachedPartial(
this HtmlHelper htmlHelper,
string partialViewName,
object model,
int cachedSeconds,
bool cacheByPage = false,
bool cacheByMember = false,
ViewDataDictionary viewData = null,
Func<object, ViewDataDictionary, string> contextualKeyBuilder = null);
存在一个重载,允许在
@Html.CachedPartial(
"PartialView",
MyModel3,
3600,
cacheByPage: true,
contextualKeyBuilder: (model, viewData) =>
{
return (model as MyViewModel).Id.ToString();
});
用例就是:
Facebook token