无法对空引用执行运行时绑定,但它不是空引用 [英] Cannot perform runtime binding on a null reference, But it is NOT a null reference

查看:37
本文介绍了无法对空引用执行运行时绑定,但它不是空引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用:MVC 4、ASP.NET Razor

我收到一个错误,看起来不可能.它告诉我我正在使用空引用状态,但显然它正在设置.

控制器:

public ActionResult Index(){字典状态 = 新字典(){{ -1, "a"},{ 0, "b"},{ 1, "c"},{ 2, "d"},};//分配状态ViewBag.States = 状态;foreach(ViewBag.States 中的 KeyValuePair de){Debug.WriteLine(de.Key);}返回视图();}

视图:

<选择>@foreach(ViewBag.States 中的 KeyValuePair de){<option value="@de.Key">@de.Value</option>}</选择>

错误:

无法对空引用执行运行时绑定第 54 行:@foreach(ViewBag.States 中的 KeyValuePair de)

解决方案

找到解决方案:我的视图中有错别字,ViewBag.Typo <-- 这导致了错误,但调试器将异常放在了不相关的地方.

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)

解决方案

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

这篇关于无法对空引用执行运行时绑定,但它不是空引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆