Subby
Subby

Reputation: 5480

MVC NullReferenceException

When I am sending information to the Database in MVC and I am redirecting the page and calling the view which prints out the newly stored data, I get a NullReferenceException error:

"Object reference not set to an instance of an object."

Apparently, my Model is null:

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.CustomerID)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Address)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
        @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
        @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
    </td>
</tr>
}

This is my Controller:

public ActionResult Index()
    {
        var customer = db.Customer.ToList();
        return View();
    }

Which gets called by:

        [HttpPost]
    public ActionResult Create(CustomerModel customer)
    {
        db.Customer.Add(customer);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

I don't understand why it's null....

Upvotes: 0

Views: 1657

Answers (1)

Jared
Jared

Reputation: 6060

public ActionResult Index()
    {
        var customer = db.Customer.ToList();
        return View(customer);
    }

You are never passing the customer object to the view.

Edit: Also not wrapping your db.SaveChanges(); in a try/catch can be dangerous when an exception occurs.

Upvotes: 3

Related Questions