I understand how this error is coming about, but I don't get why. The context makes no sense to me. Allow me to explain:
This is my "Customers/details.cshtml" View for a super simple page:
@model Vidly.Models.Customer
@{
ViewBag.Title = Model.Name;
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@Model.Name</h2>
<ul>
<li>@Model.MembershipType.Name</li>
@if (Model.Birthday.HasValue)
{
<li>@Model.Birthday.Value.ToShortDateString()</li>
}
</ul>
The Line <li>@Model.MembershipType.Name</li>
is creating the following error:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
I get it, its telling me I need to create an instance to use this property... But why??? The thing that is confusing the heck out of me is that without that single line of code, everything else on the page works fine. Why is it that Model.MembershipType.Name requires an instance but Model.Name
does not and Model.Birthday.Value.ToShortDateString()
does not???
On my Customers/index.cshtml page, I have the following code block:
Note my removal of unnecessary code noted by "...":
@model IEnumerable<Vidly.Models.Customer>
...
@foreach (var customer in Model)
{
<tr>
<td>@Html.ActionLink(customer.Name, "Details", "Customers", new {id = customer.Id}, null)</td>
<td>@customer.MembershipType.Name</td>
</tr>
}
Obviously, this foreach is instantiating an object of the Customer Model and in fact this implementation of the MembershipType.Name is working just fine... But, I don't need to iterate over it in the Details page, so if it is absolutely necessary to create an object (I still don't see why), what is the best way to do it?
EDIT: Added Controller code:
public ActionResult Details(int id)
{
var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
if (customer == null)
return HttpNotFound();
return View(customer);
}