c# - 无法对空引用执行运行时绑定(bind),但它不是空引用

标签 c# asp.net asp.net-mvc razor

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

相关文章:

c# - 随机获取选中的行号返回0

c# - 如何使用 .NET Core 绘图?

c# - 如何使输入字段可选?

asp.net - 存储数据以供客户端导出。我有一团糟

c# - 在 web.config 中放置连接字符串的位置

c# - 我如何才能在 Visual Studio 中找到所有未调用的方法?

c# - QueryString containing\coming through with\\

c# - 压缩文件时限制内存使用

asp.net - 从 AuthorizeAttribute 过滤器中获取 cookie

asp.net-mvc - 在 MVC6 中处理 IActionResult