使用:MVC 4、ASP.NET Razor
我收到一个看起来不应该发生的错误。它告诉我我正在使用一个空引用,States,但很明显它正在被设置。
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();
}
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)
最佳答案
找到解决方案:我的 View 中有错字,ViewBag.Typo <-- 这导致了错误,但调试器将异常放在了不相关的地方。
关于c# - 无法对空引用执行运行时绑定(bind),但它不是空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19457804/