1

我对 ASP.NET MVC 很陌生,所以这可能是一个简单的问题。我按照W3 Schools Movies 教程创建了一个小型数据库,其中包含我想用作博客文章并列出在主索引上。这是我当前的 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。希望这对你有用。

4

1 回答 1

1

System.NullReferenceException表示某事为空。在这种情况下,很可能Modelnull。确保控制器正在传递模型。

于 2013-01-10T09:22:22.303 回答