2016-06-22 22 views
0

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

 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 ? 
     } 
    } 

回答

3

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

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

这是正确的解决方案,谢谢! :) – perkes456