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.