Unexpected NullReferenceException in View
asp.net-mvc, asp.net-mvc-4, razor
Solution
You provide an empty default model which does nothing. It will be just so the Model isn't null. It will help to have an IsEmpty property . Better yet, if it can be applied in your case, a model with default values. The important thing is the Model not being null ever
Problem
I have a Razor view that starts like: ``` @using My.Models @model MySpecificModel @{ ViewBag.Title = "My Title"; // NullReferenceException here: string dateUtc = (Model == null ? DateTime.UtcNow.ToShortDateString() : Model.Date.ToShortDateString()); ``` I see no reason for the NullReferenceException in the last line (note: the " = ? :" stuff is on one line in my source code. It is formatted to fit here.) I then remove the declaration of/assignment to `dateUtc` and the NullReferenceException moves up to the ViewBag.Title line: ``` @using My.Models @model MySpecificModel @{ ViewBag.Title = "My Title"; // NullReferenceException here: ``` How can this possibly happen? `ViewBag` is of course not null. NOTE 1: This only happens if `Model` is null. NOTE 2: MySpecificModel.Date is of type DateTime, so can never be null.