Reputation: 691
I have a view that contains a variable i am getting out of the ViewData dictionary. The code looks like
@{
ParentModel parent = (ParentModel)ViewData["Parent"];
}
I though ok, its becuase the object does not exist in the ViewData Dictionary so i should soft cast it and check to see if it is null before using it. So i changed it to
@{
ParentModel parent = ViewData["Parent"] as ParentModel;
}
but i still get a null reference exception on this line. So to test something i changed it to
@{
ParentModel parent = new ParentModel();
}
and it still throws an exception. What on earth is going on, why would instantiating an object in a view throw a null reference exception?
I removed an unused reverence at the top of the view which resharper was letting me know of and the next using reference displayed this error
"there is no build provider registered for the extension cshtml"
I think something is wrong with ASP.Net, looking online some people suggest adding something to the Web.config, but i checked version control and this has not changed, why would this issue just start happening
Upvotes: 0
Views: 116
Reputation: 691
It turned out to be caused the model itself being null that was being used in a display template view, the model being completely different to the Parent object that was being retrieved from the ViewData and the line where the exception was being thrown.
I'm not sure why VS would break on the wrong line, but it could be because the this code block was the very first list after the model declaration. for example
@using MyProject.Models
@model ItemModel <---- VS2010 should break here
@{
ItemModel parent = ViewData["Parent"] as ItemModel; <-----VS2010 Breaks here
}
<h2>@Model.Title</h2>
Upvotes: 0
Reputation: 27944
If you get a null reference exception in this line:
@{
ParentModel parent = ViewData["Parent"] as ParentModel;
}
Then the ViewData it self is null. You have to instantiate the ViewData before using it.
Upvotes: 1