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

使用: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) 

find的解决scheme:我在我的视图中有错字,ViewBag.Typo < – 这导致了错误,但debugging器把exception放在一个不相关的地方。

当使用reflectiondynamic更新不存在的属性时,也会引发此exception。

如果使用reflection来dynamic更新属性值,那么值得检查以确保传递的PropertyName与实际属性相同。

在我的情况下,我试图更新Employee.firstName ,但该属性实际上是Employee.FirstName

值得记住。 🙂

当您的razor代码调用方法中不存在ViewBag时,会发生此错误。

调节器

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

剃刀:

 <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> 

出于某种原因,.net无法在正确的行中显示错误。 通常这会造成很多浪费时间。

我对这个错误的解决方法是从@Model.Id引用另一个项目的副本和粘贴。 这个特定的页面没有模型,但是错误行与我从未发现过的实际错误差得很远!

您必须定义不等于null的状态。

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

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

作为函数之外的属性,在函数内部插入条目,它应该工作。