无法对空引用执行运行时绑定,但它不是空引用

使用: MVC 4,ASP.NET Razor

我收到一个看起来不可能的错误。它告诉我,我正在使用一个空引用,国家,但显然它是被设置。

总监:

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();
}

观点:

<div class="search-input">
<select>
@foreach (KeyValuePair<int, string> de in ViewBag.States)
{
<option value="@de.Key">@de.Value</option>
}
</select>
</div>

错误是:

Cannot perform runtime binding on a null reference
Line 54: @foreach (KeyValuePair<int, string> de in ViewBag.States)
171401 次浏览

Set

 Dictionary<int, string> states = new Dictionary<int, string>()

as a property outside the function and inside the function insert the entries, it should work.

Found solution: I had typo in my view, ViewBag.Typo <-- this caused the error, but the debugger placed the exception at a irrelevant place.

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 actually Employee.FirstName.

Worth keeping in mind. :)

You must define states not equal to null..

@if (ViewBag.States!= null)
{
@foreach (KeyValuePair<int, string> de in ViewBag.States)
{
value="@de.Key">@de.Value
}
}

This error happens when you have a ViewBag Non-Existent in your razor code calling a method.

Controller

public ActionResult Accept(int id)
{
return View();
}

razor:

<div class="form-group">
@Html.LabelFor(model => model.ToId, "To", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.Flag(Model.from)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input value="@ViewBag.MaximounAmount.ToString()" />@* HERE is the error *@
</div>
</div>

For some reason, the .net aren't able to show the error in the correct line.

Normally this causes a lot of wasted time.

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!

Not related to Razor, you'll see that exception in runtime trying access not existed property inside the dynamic value:

dynamic myValue;
if(myValue.notExistedProperty == "some-value") { ... }