无法执行上运行空引用约束力,但它不是一个空引用 [英] Cannot perform runtime binding on a null reference, But it is NOT a null reference

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

问题描述

使用:MVC 4,ASP.NET剃刀

我收到看起来像它不应该是可能的错误。它告诉我,我使用的空引用,国,但显然它被设置。

控制器:

 公众的ActionResult指数()
{
    字典< INT,串>状态=新词典< INT,串>()
    {
        {-1,一个},
        {0,B},
        {1,C},
        {2,D},
    };    //分配状态
    ViewBag.States =状态;    的foreach(KeyValuePair< INT,串>德在ViewBag.States)
    {
        的Debug.WriteLine(de.Key);
    }
    返回查看();
}

视图:

 < D​​IV CLASS =搜索输入>
    <选择>
        @foreach(KeyValuePair< INT,串>德在ViewBag.States)
        {
            <期权价值=@ de.Key> @ de.Value< /选项>
        }
    < /选择>
< / DIV>

错误:

 无法对null引用执行运行时绑定
54号线:@foreach(KeyValuePair< INT,串>德在ViewBag.States)


解决方案

找到解决办法:我有错字在我看来,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天全站免登陆