Episerver检查内容区域是否为空

时间:2016-06-22 08:19:46

标签: c# asp.net-mvc episerver

我需要检查内容区域是否为空但是我收到错误“对象引用未设置为实例”,这是我的页面控制器,我也试过currentPage.TabContentArea.IsEmpty,仍然是同样的错误。内容区域为空,这是我第一次尝试运行它所以我需要在if语句中执行代码之前检查它是否为空。

     public class StandardPageController : PageController<StandardPage>
    {
        // GET: StandardPage
        public   ActionResult Index( StandardPage currentPage)
        {

            // this collection should be used in foreach loops
            var tabItems = new List<TabViewModel>();


//this is where I get error
            if(currentPage.TabContentArea.FilteredItems.Any())

 { 
            var contentAreaItems = currentPage.TabContentArea.FilteredItems.ToList();
            var contentLoader = ServiceLocator.Current.GetInstance<IContentLoader>();

            foreach (var contentAreaItem in contentAreaItems)
            {
                // get an instance of Tab Block
                // If you didn't set any restrictions, ContentArea can contain anything.
                // We need to check if blockData is of type PageTab
                var blockData = contentLoader.Get<PageTab>(contentAreaItem.ContentLink);
                if (blockData == null) continue;

                tabItems.Add(new TabViewModel
                {

                    Id = Guid.NewGuid(),
                    Title = blockData.TabTitle,
                    Text = blockData.TabContent
                });
            }
            ViewBag.items = tabItems;
            }
            return View(); // Should I return tabitems here ?
        }
    }

1 个答案:

答案 0 :(得分:4)

ContentArea属性可以为null,因此您需要先检查currentPage.TabContentArea是否为null。

if(currentPage.TabContentArea != null && currentPage.TabContentArea.FilteredItems.Any()) { ... }