【问题标题】:NullReferenceException when using foreach loop in Model在模型中使用 foreach 循环时出现 NullReferenceException
【发布时间】:2017-01-07 19:19:49
【问题描述】:

我一直在尝试使用 foreach 显示数据库表中的数据,但是我收到了这个错误:

App_Web_tncl0rkz.dll 中出现“System.NullReferenceException”类型的异常,但未在用户代码中处理。

错误:@foreach(模型中的 var img)

当我尝试访问 View 时,应用程序崩溃并导致上述错误。

这是我的 View 的 HTML 代码 C#,因为我正在使用 Visual Studio 进行编程

@model IEnumerable<Common.Image>
....
<table class="table">
    <tr>
        <th>@Html.DisplayNameFor(model => model.imagePath)</th>
        ....
    </tr>
    @foreach (var img in Model)
    { 
        <tr>
            <td>@Html.DisplayFor(imgItem => img.imagePath)</td>
            ....
        </tr>
    }
</table>

这是我的 Controller's C# 代码。

[Authorize(Roles="Admin")]
public ActionResult UsersGallery(string username)
{
    ImagesBL imgBl = new ImagesBL();
    Image img = imgBl.GetImage(username);
    return View(img);
}

【问题讨论】:

  • 不需要foreach,只使用foreach 列表集合。似乎 img 只是一个对象。去掉 foreach 试试看
  • 请注意,model-view-controller 标签是针对有关模式的问题。 ASP.NET-MVC 实现有一个特定的标签。

标签: c# html asp.net-mvc


【解决方案1】:

您似乎正在尝试迭代一个不是集合的对象。在您的控制器中,您传递的是单个“图像”而不是集合。但是,您的特定错误是空引用异常,因此看起来“模型”在到达视图时可能为空。在某些时候(无论是在控制器中,还是在视图中),您都需要在尝试访问对象的任何属性之前检查对象是否为空,否则您将获得空引用异常。

【讨论】:

    【解决方案2】:

    您从控制器操作发送单个图像 (return View(img);),而 View 绑定到图像对象的集合 (@model IEnumerable&lt;Common.Image&gt;)。即使包含单个图像,您也需要发送图像集合。在 action 方法中更改以下语句

    return View(img);
    

    return View(new List<Image>(){img});
    

    【讨论】:

    • 这个我试过了,没有出现错误。 View 启动,然后是表头,但不是 foreach 语句(包含迭代数据)。你知道可能是什么原因吗?再次感谢您的帮助!
    【解决方案3】:

    您只返回了对象(图像的 img 类型)而不是集合列表。

    Use Foreach for the collection only.如果你没有将集合传递给查看,那么你可以直接在模型中访问它。

    您的代码:如果 img 不是集合,请删除 foreach。

    <tr>
                    <td>
                        @Html.DisplayFor(model => model.imagePath)
                    </td>
                    <td>
                        @Html.DisplayFor(model => model.Signature)
                    </td>
                    <td>
                        @Html.DisplayFor(model => model.Username)
                    </td>
    
                    <td>
                        @Html.ActionLink("Download", "Download", new { username = Model.Username }) 
                    </td>
                </tr>
    

    【讨论】:

      猜你喜欢
      • 2020-08-26
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多