如何获取特定页面类型构建器类型的 EPiServer 页面,并正确填充其所有强类型属性?我可以在一个方法调用中做到这一点吗?
我试过使用:
ContentPageType pageAsContentPageType =
DataFactory.Instance.GetPage<ContentPageType>(page.PageLink);
但是,这不起作用。尽管我将其目标指定为 ContentPageType,但它只填充 PageData 属性。
我在下面包含了有问题的代码,我对此进行了广泛的评论:
public static IList<ContentPageType> GetMapEnabledPages()
{
// Get the content pages
IList<PageData> pages = PageFactory.GetPages(
PageReference.StartPage.ID,
BaseSettings.Constants.EPiServer.PageTypeNames.ContentPage
);
// Some content pages will be map enabled pages. So, we need to extract the ones that are put them in this variable.
IList<ContentPageType> mapEnabledPages = new List<ContentPageType>();
// walk pages to extract only map enabled pages
foreach (PageData page in pages)
{
// get the page as a ContentPageType.
// unfortunately, this method only populates the PageData information and none of the additional strongly types properties that a ContentPageType has.
// we would expect this happen because EPiServer uses IoC elsewhere but does not do it here.
ContentPageType pageAsContentPageType =
DataFactory.Instance.GetPage<ContentPageType>(page.PageLink);
// So, we fudge it - we know that the PageData weakly type properties has IsMapEnabled correctly populated.
// So, we put that value in the strongly typed ContentPageType property.
if (pageAsContentPageType != null && pageAsContentPageType["IsMapEnabled"] != null)
{
// put that the weakly typed property for "IsMapEnabled" into the strongly typed ContentPageType IsMapEnabled property
pageAsContentPageType.IsMapEnabled =
TypeHelper.ConvertToBoolean(pageAsContentPageType["IsMapEnabled"].ToString());
// check if it is map enabled
if (pageAsContentPageType.IsMapEnabled)
{
// it is a map enabled page. So, add it to the mapEnabledPages list.
mapEnabledPages.Add(pageAsContentPageType);
}
}
}
return mapEnabledPages;
}
编辑:
以前,我尝试了以下方法,但它也不起作用:
ContentPageType pageAsContentPageType =
DataFactory.Instance.GetPage(page.PageLink) as ContentPageType
CMS5R2SP2 的解决方案:
结果发现 IsMapEnabled 页面类型属性上缺少虚拟关键字。因此,IoC 容器不会从其默认值覆盖此属性。这是最终的实现:
IList<PageData> pages = PageFactory.GetPages(
PageReference.StartPage.ID,
BaseSettings.Constants.EPiServer.PageTypeNames.ContentPage
);
// Some content pages will be map enabled pages.
// So, we need to extract the ones that are put them in this variable.
IEnumerable<ContentPageType> mapEnabledPages =
from page in pages.OfType<ContentPageType>()
where page.IsMapEnabled
select page;
// return map enabled pages.
return mapEnabledPages.ToList();
CMS6 的解决方案:
OfType<ContentPageType>()
不起作用。因此,重新获取每一页就像 Joel 所说的那样。