小编gen*_*der的帖子

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

使用: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();
}
Run Code Online (Sandbox Code Playgroud)

风景:

<div class="search-input">
    <select>
        @foreach (KeyValuePair<int, string> de in ViewBag.States)
        {
            <option value="@de.Key">@de.Value</option>
        }
    </select>
</div>
Run Code Online (Sandbox Code Playgroud)

错误:

Cannot perform runtime binding on a null reference
Line 54: @foreach (KeyValuePair<int, string> de in ViewBag.States)
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc razor

67
推荐指数
5
解决办法
11万
查看次数

标签 统计

asp.net ×1

asp.net-mvc ×1

c# ×1

razor ×1