【发布时间】:2014-05-09 02:43:23
【问题描述】:
尝试使用 MVC 从我的数据库中删除记录时,我不断收到错误消息。这个错误是什么意思?我做错了什么?
这是我的控制器操作:
public ActionResult Delete(int id)
{
Person somePerson = db.People
.Where(p => p.Id == id) //this line says to find the person whose ID matches our parameter
.FirstOrDefault(); //FirstOrDefault() returns either a singluar Person object or NULL
db.Entry(somePerson).State = System.Data.Entity.EntityState.Deleted;
db.SaveChanges();
return View("Index");
}
这是我的观点:
@using sample.Models
@model List<Person>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<!-- Html.ActionLink is the MVC equivalent of <a href="..."></a>
-->
@Html.ActionLink("Create new person", "Create")
<table>
<tr>
<th></th>
<th></th>
<th>Email Address</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<!-- Loop through our List of People and create a new TR for each item -->
@foreach(Person person in Model) //Error Occurs on this line
{
<tr>
<td></td>
<td>@Html.ActionLink("Edit", "Edit", new { id = person.Id })</td>
<td>@Html.ActionLink("Delete", "Delete", new { id = person.Id })</td>
<!-- Using the @@ tag will inject the object's value into HTML -->
<td>@person.Email</td>
<td>@person.FirstName</td>
<td>@person.LastName</td>
</tr>
}
</table>
</div>
</body>
</html>
编辑和创建工作正常。当我添加删除时,我开始遇到问题。这是我得到的异常,模型为空仅供参考
An exception of type 'System.NullReferenceException' occurred in App_Web_rczw3znb.dll but was not handled in user code
【问题讨论】:
-
是的,你得到空异常,因为你的视图试图访问模型,但你没有将任何模型传递给它......所以模型是空的。不难理解为什么。
-
这不能解决你的问题,但仅供参考,
x.Where(condition).FirstOrDefault()可以写成x.FirstOrDefault(condition)。
标签: c# asp.net-mvc nullreferenceexception