Reputation: 5002
I have searched SO for similar posts and have not been successful with any given solutions. So I have posted this again.
I am trying to post some information back to the database in this Controller Action. This Action is called when Save button is clicked on the View.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditDetail(int id, FormCollection fvals)
{
Environments env = environmentsRepository.GetEnvironmentDetail(id);
UpdateModel(env);
environmentsRepository.Save();
return RedirectToAction("List", new RouteValueDictionary(new
{controller="Environments", action="List", id = 1}));
}
When I click on the Save button, I get the following error:
Line 32:
Line 33:
Line 34: <% foreach (var environment in Model) <--Error in this line
Line 35: { %>
Line 36:
[NullReferenceException: Object reference not set to an instance of an object.]
ASP.views_environments_list_aspx.__RenderContent2(HtmlTextWriter __w, Control parameterContainer) in e:\code\ossp\WebUI\Views\Environments\List.aspx:34
Please let me know what I am missing? How do I resolve the error?
List View:
http://pastebin.ubuntu.com/544767/
List Action:
http://pastebin.ubuntu.com/544768/
Resolution:
I have realized that I was passing the wrong parameter 'id' instead of 'page', to the List view.
Thanks everyone for their pointers. I was able to learn a lot due to this discussion. Unfortunately, I am still at 11 to be able to give some votes. Thanks!
Upvotes: 0
Views: 2378
Reputation: 5366
"Page" does not have a value, so as Ahmad pointed out it looks like you are returning back an empty View as per the ELSE
if (page.HasValue)
return View(environmentsRepository.Environments.Skip(((int)page - 1) * PageSize).Take(PageSize).ToList());
else
return View(); ///TODO Handle This
Have you tried debugging through to see what flow the code takes?
Upvotes: 1
Reputation: 1038790
The problem is that inside your EditDetail
at the end you are redirecting to the List
action of the Environments
controller and I suppose that this action renders a strongly typed view. The problem is that the model you passed to the view was null. So your controller action might look something like this:
public ActionResult List(int id)
{
var model = FetchModelFromSomewhere(id); // this probably returns null here
return View(model);
}
And inside your view you are trying to enumerate over the model which is null:
<% foreach (var environment in Model) { %>
and you are getting the exception. So make sure that the model you are passing to the List
view is not null.
Upvotes: 2