Null Conditional Operator for fallback images

Tonight when working on my new version of Owain.Codes I managed to blow up the site. The reason? I hadn't put an image in to the CMS and when I rendered out the image or the lack of an image on the front end, I got a null exception error.

I started to write a bit of code to handle this which looked a bit like

@if(Model.Image.Url() == null)
  set default image as fallback.jpg
  use the image from the CMS

But then I thought, there must be a nicer way to handle fallbacks, and I believe I have found that nicer option and its by using the Null Conditional Operator

So I am now using:

 var blogImage = Model.PageBanner?.Url() ?? "assets/images/noImage.jpg";

So if the Model.PageBanner is null, give me the noImage.jpg fall back string, else give me the Model.PageBanner.Url().

I then use the variable blogImage on my page.

I now don't need to worry about whether I set an image for a blog or not. Either way I will have an image on my page.

Published on: 10 December 2020