我是ASP.NET MVC的新手,所以这可能是一个简单的问题。我按照W3 Schools Movies tutorial创建了一个小型数据库,其中包含字段Naslov(我的语言为“Heading”)Sadrzaj(我的语言为“内容”)和Datum(“Date”),我想将其用作博客帖子和主要指数列表。这是我目前的Aktuelnosti.cs代码
namespace comp_2000.Models
{
public class Aktuelnosti
{
public int ID { get; set; }
public string Naslov { get; set; }
public string Sadrzaj { get; set; }
public DateTime Datum { get; set; }
}
public class AktuelnostiContext : DbContext
{
public DbSet<Aktuelnosti> Aktuelnosti { get; set; }
}
}
这是我在Aktuelnosti中的Index.cshtml的相关视图,它的工作原理
@model IEnumerable<comp_2000.Models.Aktuelnosti>
<table border="1">
<tr>
<th>
@Html.DisplayNameFor(model => model.Naslov)
</th>
<th>
@Html.DisplayNameFor(model => model.Sadrzaj)
</th>
<th>
@Html.DisplayNameFor(model => model.Datum)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td width="20%">
@Html.DisplayFor(modelItem => item.Naslov)
</td>
<td width="60%">
@Html.DisplayFor(modelItem => item.Sadrzaj)
</td>
<td>
@Html.DisplayFor(modelItem => item.Datum)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Preview", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
所以,当我在Home里面为Index.cshtml尝试相同的代码时,看起来像这样
@model IEnumerable<comp_2000.Models.Aktuelnosti>
@foreach (var item in Model)
{
<p>@Html.DisplayFor(modelItem => item.Naslov)</p>
<p>@Html.DisplayFor(modelItem => item.Sadrzaj)</p>
<p>@Html.DisplayFor(modelItem => item.Datum)</p>
<hr>
}
我明白了
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 48:
Line 49:
Line 50: @foreach (var item in Model)
Line 51: {
Line 52: <p>@Html.DisplayFor(modelItem => item.Naslov)</p>
它说问题出在foreach循环中。我做错了什么?我只想在两个不同的页面上显示来自一个数据库的相同数据。
编辑:还有一些关于NullReferenceException的内容未被用户代码处理。希望这对你有用。
答案 0 :(得分:1)
System.NullReferenceException
表示某些内容为空。在这种情况下,Model
很可能是null
。确保控制器正在通过模型。