Spodworld

a collection of technical fixes and other randon stuff

How to solve weird System.NullReferenceException on MVC view


Problem

When developing an MVC view, i obtained an error as the view was being displayed:
"An exception of type 'System.NullReferenceException' occurred in App_Web_motvehmanualmatchitemview.cshtml.23260864.l4awxamh.dll but was not handled in user code"
or
"NullReferenceException was unhandles by user code"

Having checked the model and the value reported, I found neither were null.
Sometime the debug process reported it occurred on line 0 (zero). The error messages were indeed misleading


Solution

This is misleading and it's because the debugger cannot decide which line of code the error is occurring.
It most likely isn't on the line highlighted.
Instead check the lines of code following it. Specifically for any properties that you may be modifying.

For example... my code was reporting an error with this line:
@Html.HiddenFor(m => m.Id)
But was actually erroring here ....

'@Model.PurchaserForename.Trim()','@Model.PurchaserInitials.Trim()','@Model.DOB.ToString()

 This was because i had mocked up the dataa and hadn't got round to setting PurchaserForename/PurchaserInitials/PurchaserSurname


Hope that helps!

 

Loading