Hi guys, I'm having a little trouble with creating an edit control method within my application. I have posted both the edit viewpage and controller for the edit method. It pulls the information from the database fine but when I go to edit anything and post
it back it brings up the object reference error on line 18 of the edit page.
Any help would be greatly appreciated.
HOME CONTROLLER:
using UniApp.Controllers;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using UniApp.Models;
using System;
namespace UniApp.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
private UniversityNewsEntities _db = new UniversityNewsEntities();
public ActionResult Index()
{
var results = from t in _db.News
orderby t.posted descending
select t;
return View(results);
}
//
// GET: /Home/Details/5
public ActionResult Details(int id)
{
var result = (from p in _db.News
where p.storyId == id
select p).FirstOrDefault();
return View(result);
}
// GET /Home/ViewResults/
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string header)
{
var search = (from q in _db.News
where q.headline.Contains(header)
orderby q.posted descending
select q);
int count = search.Count();
ViewData.Add("count", count);
ViewData.Model = search;
ViewData.Add("type", header);
switch (count)
{
case 0:
ViewData["MessageCountString"] = "no messages";
I did try your code in my controller all star and it's still coming up with the same error. Like I said before it will pull the information from the database fine in order for me to edit. But once i go to submit anything that I have edited it brings back
the error:
Object reference not set to an instance of an object.
Description:
An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 16: <p> Line 17: <label for="posted">posted:</label> Line 18: <%= Html.TextBox("posted", String.Format("{0:g}", Model.posted)) %> Line 19: <%= Html.ValidationMessage("posted", "*") %> Line 20: </p>
I was wondering if it would be easier to try and throw all my existing code into a repository as the editing and creating looks to be a lot easier to figure out once it's in a repository.
// POST: /Home/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(News productToEdit)
{
try
{
var originalProduct = (from p in _db.News
where p.storyId == productToEdit.storyId
select p).FirstOrDefault();
_db.ApplyPropertyChanges(originalProduct.EntityKey.EntitySetName,
productToEdit);
_db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Most likely in the above controller action, some exception is happening and it is going into the catch clause wherein you are returning "edit" view. That edit view is expecting some Model, but since you are not returning any (you are doing return View();)
therefore you are getting object reference error.
You can put a breakpoint on catch clause and see for yourself.
You can replace it with return View(productToEdit); and it should work (this may not be the eventual solution). This will give you a hint where your controller and view are failing.
I tried the return view(productToEdit) and it's not giving the null object error but saying it within my edit page itself now.
After all this headache would it be better to try split my code into a repository because once ive got edited and create and delet I need to start getting it into some form of paging.
scarfey
Member
6 Points
26 Posts
Object reference not set to an instance of an object.
Nov 25, 2010 11:23 AM|LINK
Hi guys, I'm having a little trouble with creating an edit control method within my application. I have posted both the edit viewpage and controller for the edit method. It pulls the information from the database fine but when I go to edit anything and post it back it brings up the object reference error on line 18 of the edit page.
Any help would be greatly appreciated.
HOME CONTROLLER:
using UniApp.Controllers;
using System.Linq;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using UniApp.Models;
using System;
namespace UniApp.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
private UniversityNewsEntities _db = new UniversityNewsEntities();
public ActionResult Index()
{
var results = from t in _db.News
orderby t.posted descending
select t;
return View(results);
}
//
// GET: /Home/Details/5
public ActionResult Details(int id)
{
var result = (from p in _db.News
where p.storyId == id
select p).FirstOrDefault();
return View(result);
}
// GET /Home/ViewResults/
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string header)
{
var search = (from q in _db.News
where q.headline.Contains(header)
orderby q.posted descending
select q);
int count = search.Count();
ViewData.Add("count", count);
ViewData.Model = search;
ViewData.Add("type", header);
switch (count)
{
case 0:
ViewData["MessageCountString"] = "no messages";
break;
case 1:
ViewData["MessageCountString"] = "one message";
break;
default:
ViewData["MessageCountString"] = "messages : " + count;
break;
}
return View();
}
//
// GET: /Home/Edit/5
public ActionResult Edit(int id)
{
var productToEdit = (from p in _db.News
where p.storyId == id
select p).FirstOrDefault();
return View(productToEdit);
}
//
// POST: /Home/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(News productToEdit)
{
try
{
var originalProduct = (from p in _db.News
where p.storyId == productToEdit.storyId
select p).FirstOrDefault();
_db.ApplyPropertyChanges(originalProduct.EntityKey.EntitySetName,
productToEdit);
_db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
EDIT VIEWPAGE
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<UniApp.Models.News>"%>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Edit</h2>
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="posted">posted:</label>
<%= Html.TextBox("posted", String.Format("{0:g}", Model.posted)) %>
<%= Html.ValidationMessage("posted", "*") %>
</p>
<p>
<label for="headline">headline:</label>
<%= Html.TextBox("headline", Model.headline) %>
<%= Html.ValidationMessage("headline", "*") %>
</p>
<p>
<label for="story">story:</label>
<%= Html.TextBox("story", Model.story) %>
<%= Html.ValidationMessage("story", "*") %>
</p>
<p>
<label for="image">image:</label>
<%= Html.TextBox("image", Model.image) %>
<%= Html.ValidationMessage("image", "*") %>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
ignatandrei
All-Star
137682 Points
22147 Posts
Moderator
MVP
Re: Object reference not set to an instance of an object.
Nov 25, 2010 11:42 AM|LINK
What's the line 18 ?
anyway, please replace:
with
var productToEdit = (from p in _db.News
where p.storyId == id
select p).FirstOrDefault();
if(productToEdit == null)
return Content(" not found product with id = " + id);
else
return View(productToEdit)
scarfey
Member
6 Points
26 Posts
Re: Object reference not set to an instance of an object.
Nov 25, 2010 12:00 PM|LINK
Hi,
Sorry I should of put what line 18 was, it's:
<%= Html.TextBox("posted", String.Format("{0:g}", Model.posted)) %>
Even when I commented it out it popped to the next textbox. I was thinking it might have something to do with the Model bit but i'm unsure.
Thanks for the speedy response
Jason
ignatandrei
All-Star
137682 Points
22147 Posts
Moderator
MVP
Re: Object reference not set to an instance of an object.
Nov 25, 2010 12:37 PM|LINK
For sure. The " firstordefault" code means " give me null if you do not find anything in database"
Please try my code in controller action.
scarfey
Member
6 Points
26 Posts
Re: Object reference not set to an instance of an object.
Nov 25, 2010 12:45 PM|LINK
I did try your code in my controller all star and it's still coming up with the same error. Like I said before it will pull the information from the database fine in order for me to edit. But once i go to submit anything that I have edited it brings back the error:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Source File: c:\Users\Jason\Desktop\UniApp\UniApp\Views\Home\Edit.aspx Line: 18
Stack Trace:
Version Information: Microsoft .NET Framework Version:2.0.50727.4952; ASP.NET Version:2.0.50727.4955
ignatandrei
All-Star
137682 Points
22147 Posts
Moderator
MVP
Re: Object reference not set to an instance of an object.
Nov 25, 2010 01:37 PM|LINK
Please list your action .
scarfey
Member
6 Points
26 Posts
Re: Object reference not set to an instance of an object.
Nov 25, 2010 01:54 PM|LINK
Sorry i'm confused, my action?
I was wondering if it would be easier to try and throw all my existing code into a repository as the editing and creating looks to be a lot easier to figure out once it's in a repository.
Thanks for your help
Jason
ignatandrei
All-Star
137682 Points
22147 Posts
Moderator
MVP
Re: Object reference not set to an instance of an object.
Nov 25, 2010 02:07 PM|LINK
Yes, you have 3 action (index and details) where yuo are putting "firstordefault"
Both should handle for null
return Content(" not found product with id = " + id);
More, you have
catch
{
return View();
}
please replace with
catch(Exception ex)
{
ModelState.AddModelError("",ex.Message);
return View(THEMODEL);
}
sachingusain
Star
8786 Points
1702 Posts
Re: Object reference not set to an instance of an object.
Nov 25, 2010 02:43 PM|LINK
Most likely in the above controller action, some exception is happening and it is going into the catch clause wherein you are returning "edit" view. That edit view is expecting some Model, but since you are not returning any (you are doing return View();) therefore you are getting object reference error.
You can put a breakpoint on catch clause and see for yourself.
You can replace it with return View(productToEdit); and it should work (this may not be the eventual solution). This will give you a hint where your controller and view are failing.
Thanks.
scarfey
Member
6 Points
26 Posts
Re: Object reference not set to an instance of an object.
Nov 25, 2010 03:49 PM|LINK
Hi sachingusain,
I tried the return view(productToEdit) and it's not giving the null object error but saying it within my edit page itself now.
After all this headache would it be better to try split my code into a repository because once ive got edited and create and delet I need to start getting it into some form of paging.
Thanks for all your help so far guys