Michael van der Horst
Michael van der Horst

Reputation: 550

When I try to save an entity I get the error: Object reference not set to an instance of an object

When I try to save an entity I get an error:

Object reference not set to an instance of an object

I am able to create a new entity, the code is almost the same.

When I try to save the entity I am able to trace a bit of the code My Controller code looks like this:

  _entities.Kandidaats.Attach(kandidaatBewerken,true);
  _entities.SubmitChanges();
  return RedirectToAction("Index");

When I trace the code, I see that my kandidaatBewerken holds the right data, on the first line, after that the trace goes back to my view code and gives the error on the second line:

    <% using (Html.BeginForm()) {%>
<%= Html.TextBox("KandidaatId", Model.KandidaatId)%>

When I trace it, it says that my Model is empty, while just a handling before this one, it is filled.

Why do I get this error and how can I move forward?

Upvotes: 1

Views: 211

Answers (1)

datacop
datacop

Reputation: 602

I'm going to guess here.. because there's not a whole lot of code to go on..

But the "Index" view is creating a form to edit your Kandidaat object...

However, you're redirecting your user to the form without a populated model (which is why the second line throws an error.. model is null and you're calling a property on a null object).

try:

return RedirectToAction("Index", kandidaatBewerken);

But that will take you back to the form (which may be your desired result).. I would take the user back to whatever action generated the list, or the another route...

return RedirectToAction("List");

or

return RedirectToRoute("Home");

Upvotes: 1

Related Questions