Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected NullReferenceException in View

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.

like image 944
Eric J. Avatar asked Apr 29 '13 06:04

Eric J.


Video Answer


1 Answers

A NullReferenceException on ViewBag.Title can indicate the error is really on a nearby line. In this example the error was thrown on line 1 but the real error was the null Model.Invoice in line 3.

<h2>@ViewBag.Title</h2>
<div class="pull-right">
    <button onclick="addInvoice('@Model.Invoice.InvoiceId');">Add Invoice</button>
</div>

Also ASP.NET MVC Razor does not handle nulls in ternary statements like C# does.

//Ternaries can error in Razor if Model is null
string date = (Model == null ? DateTime.Now : Model.Date);

//Change to
string date = null;
if (Model == null)
    date = DateTime.Now;
else
    date = Model.Date;
like image 122
SushiGuy Avatar answered Sep 28 '22 08:09

SushiGuy