Unexpected NullReferenceException in view

I have a Razor view that starts as:

@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 to throw a NullReferenceException on the last line (note: the material "= ?:" is on the same line in my source code. It is formatted to be here.)

Then I delete the declaration / assignment in dateUtc , and the NullReferenceException throws up the ViewBag.Title line:

 @using My.Models @model MySpecificModel @{ ViewBag.Title = "My Title"; // NullReferenceException here: 

How can this happen? ViewBag , of course, is not null.

NOTE 1 : This only happens if Model is null.

NOTE 2 : MySpecificModel.Date is of type DateTime, so it can never be null.

+6
source share
3 answers

You provide an empty default model that does nothing. It will be just so that the model is not null. This will help to create the IsEmpty property. Even better, if this can be applied in your case, a model with default values. The important thing is that the Model has not been zero ever

+3
source

You will get an empty exception if you do not pass any model to the view and still have the view attached to the model, for example:

 @model MySpecificModel 

If you did not pass such a model to the view from your controller.

+3
source

A NullReferenceException in the ViewBag.Title may indicate that the error is indeed on a nearby line. In this example, an error was selected on line 1, but the null model was the real error. Invoice on 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 null values ​​in 3D expressions, such as C #.

 //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; 
+3
source

Source: https://habr.com/ru/post/943857/


All Articles