【发布时间】: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