尝试使用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>
编辑和创建工作正常。当我添加删除是我开始得到问题的地方。这是我得到的例外,Model是null FYI
An exception of type 'System.NullReferenceException' occurred in App_Web_rczw3znb.dll but was not handled in user code
答案 0 :(得分:1)
您需要为Index
视图提供模型。您在Create
和Edit
中执行了此操作..但您不在Delete
。
所以,像这样:
return View("Index", listOfPeopleHere);
此外,您似乎将View用作整个页面。您应该真正考虑使用Layout
..以便在每个视图中不需要页面顶部的样板代码。
答案 1 :(得分:0)
public ActionResult Delete(int id)
{
//Find the person in the DB. Use the supplied "id" integer as a reference.
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
if (ModelState.IsValid)
{
db.People.Remove(somePerson);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(somePerson);
}