using: MVC 4, ASP.NET Razor
I'm getting an error that looks like it shouldn't be possible. It tells me that i'm using a null-reference, States, but clearly it is being set.
Controller:
public ActionResult Index()
{
Dictionary<int, string> states = new Dictionary<int, string>()
{
{ -1, "a"},
{ 0, "b"},
{ 1, "c"},
{ 2, "d"},
};
//assigning states
ViewBag.States = states;
foreach (KeyValuePair<int, string> de in ViewBag.States)
{
Debug.WriteLine(de.Key);
}
return View();
}
The View:
<div class="search-input">
<select>
@foreach (KeyValuePair<int, string> de in ViewBag.States)
{
<option value="@de.Key">@de.Value</option>
}
</select>
</div>
The error:
Cannot perform runtime binding on a null reference
Line 54: @foreach (KeyValuePair<int, string> de in ViewBag.States)
This error happen when you have a ViewBag nonexistent in your razor code calling a method.
Controller
razor:
For some reason the .net aren't able to show the error in the correct line. Normally this cause a lot of wasted time.
Set
as a property outside the function and inside the function insert the entries, it should work.
This exception is also thrown when a non-existent property is being updated dynamically, using reflection.
If one is using reflection to dynamically update property values, it's worth checking to make sure the passed
PropertyName
is identical to the actual property.In my case, I was attempting to update
Employee.firstName
, but the property was actuallyEmployee.FirstName
.Worth keeping in mind. :)
My solution to this error was that a copy and paste from another project that had a reference to
@Model.Id
. This particular page didn't have a model but the error line was so far off from the actual error I about never found it!You must define states not equal to null..
Found solution: I had typo in my view, ViewBag.Typo <-- this caused the error, but the debugger placed the exception at a irrelevant place.