I keep getting an error when trying to delete a record from my database using MVC. What does this error mean? What am I doing wrong?
Here is my controller action:
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");
}
Here is my View:
@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>
Edit and Create Work Fine. When I added the delete is where i started to get the issues. Here is the exception I am getting and Model is null FYI
An exception of type 'System.NullReferenceException' occurred in App_Web_rczw3znb.dll but was not handled in user code