0

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....

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.