<分区>
所以我正在创建一个强类型 View 。我的模型名为 RestaurantReview.cs,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OdeToFood.Models
{
public class RestaurantReview
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public int Rating { get; set; }
}
}
我让 Visual Studio 基于此创建了一个强类型列表模型,如下所示:
@model IEnumerable<OdeToFood.Models.RestaurantReview>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.Country)
</th>
<th>
@Html.DisplayNameFor(model => model.Rating)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.Country)
</td>
<td>
@Html.DisplayFor(modelItem => item.Rating)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
当我运行网站时,在“@foreach(模型中的变量项)”行中出现空指针异常,突出显示模型对象,并指出“对象引用未设置为对象的实例。”
我什至没有真正理解这段代码怎么会出错,因为我什至没有编写它,Visual Studio 做到了。这里发生了什么?