Empty ContentArea, avoid null

ContentArea when empty (no blocks dragged) returns null in code. It’s fine when you use EPiServer standard code for handling ContentArea rendering:

@Html.PropertyFor(m => m.MyContentArea)

When it breaks

But the problem exists when you try to touch it from code

@foreach(var block in Model.MyContentArea) // NullReferenceException
{
  // ...
}

or

if(page.MyContentArea.Any()) // NullReferenceException
{
  // ...
}

Extensions as a solutions

I use extension methods, which protects me from NullReferenceException.

public static class ContentAreaExtensions
{
    public static IEnumerable<IContent> ContentsOrEmpty(this ContentArea contentArea)
    {
        return contentArea != null ? contentArea.Contents : Enumerable.Empty<IContent>();
    }

    public static IEnumerable<IContent> FilteredContentsOrEmpty(this ContentArea contentArea)
    {
        return contentArea != null ? contentArea.FilteredContents : Enumerable.Empty<IContent>();
    }
}

Custom ContentArea

There is also good reason when you develop custom ContentAreas renderings to put the code in ContentArea.cshtml, so it always check for null.

// Views\Shared\DisplayTemplates\ContentArea.cshtml

@model EPiServer.Core.ContentArea
@if(Model != null)
{
    Html.RenderBalancedContentArea(Model);
}

While you are developing the code you can forget about this things, because you have always some data there. I have just notice that in one old project there is no possibility of removing all the shared blocks from a ContentArea, because I forget about this. It was good lesson for me.

Reklamy
Ten wpis został opublikowany w kategorii EpiServer i oznaczony tagami , , . Dodaj zakładkę do bezpośredniego odnośnika.

Jedna odpowiedź na „Empty ContentArea, avoid null

  1. Great tip. I’m using extension method named With(). Looks good when chaining 🙂

    page.MyContentArea.With(ca => { … });

Możliwość komentowania jest wyłączona.