Reputation: 5002
I get this error when I invoke the Edit Action of one of my controllers.
Here is the C# code of the Edit action method
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(cedetails detailToEdit)
{
validateDetail(detailToEdit);
if (!ModelState.IsValid)
return View();
try
{
var originaldetail = (from d in entity1.cedetails
where d.detail_id == detailToEdit.detail_id
select d).FirstOrDefault();
entity1.ApplyPropertyChanges(originaldetail.EntityKey.EntitySetName, detailToEdit);
entity1.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
This is the validateDetail Method:
protected void validateDetail(cedetails detailToValidate)
{
if (detailToValidate.c_name.Trim().Length == 0)
ModelState.AddModelError("c_name", "C name is required.");
ModelState.SetModelValue("c_name", ValueProvider["c_name"]);
if (detailToValidate.a_server.Trim().Length == 0)
ModelState.AddModelError("a_server", "A server is required.");
ModelState.SetModelValue("a_server", ValueProvider["a_server"]);
if (detailToValidate.d_server.Trim().Length == 0)
ModelState.AddModelError("d_server", "D server is required.");
ModelState.SetModelValue("d_server", ValueProvider["d_server"]);
if (detailToValidate.l_server.Trim().Length == 0)
ModelState.AddModelError("l_server", "L server is required.");
ModelState.SetModelValue("l_server", ValueProvider["l_server"]);
if (detailToValidate.url.Trim().Length == 0)
ModelState.AddModelError("url", "URL is required.");
ModelState.SetModelValue("url", ValueProvider["url"]);
if (detailToValidate.s_id.Trim().Length == 0)
ModelState.AddModelError("s_id", "S ID is required.");
ModelState.SetModelValue("s_id", ValueProvider["s_id"]);
}
I get the error in this line:
<%= Html.TextBox("c_name", Model.c_name) %>
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
I have searched for this error and happened upon several solutions, but none of them worked for me. Please let me know if this can be resolved at all. I also will add that I have chosen to hide certain table columns in the view, including detail_id, by not just displaying them.
Upvotes: 0
Views: 1800
Reputation: 4624
i Think blue_fenix has apoint in his answer. it seems that you are not setting the Model Here:
if (!ModelState.IsValid)
return View();
And Here:
catch
{
return View();
}
You need to return the Model, because the HTML Textbox Helper is spectating a Model that can´t be null. On each case, try returning the same binded Model:
return View(detailToEdit);
Upvotes: 0
Reputation: 689
does your Index action set the Model? the edit action doesn't anywhere, so if the Model isn't set in the Index action (ala return View(cedetials)) then the Model will be null.
Upvotes: 2