这个问题已经在这里有了答案: > What is a NullReferenceException, and how do I fix it? 31个
因此,我正在创建一个强类型的视图.我的模型称为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基于此创建一个强类型的List模型,如下所示:
@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做到了.这是怎么回事
解决方法:
您的控制器显示已通过RestaurantReview IEnumerable.例:
public class HomeController : Controller { //suppose this is your Home
public ActionResult Index() {
IEnumerable<OdeToFood.Models.RestaurantReview> model;
model = from m in db.RestaurantReviews
... //your query here
select m;
return View(model); //pass the model here
}
那么您将不会获得null异常