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



Question:

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?


Solution:1

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");  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »