Reputation: 238
I am making an ASP.NET MVC 5 web app using EF6. Here is the Edit() method that I'm given when I add a controller:
// POST: Gift/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,Name,Description,Link,Price")] Gift gift)
{
if (ModelState.IsValid)
{
db.Entry(gift).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("View", "GiftList", new { id = gift.GiftList.ID });
}
return View(gift);
}
Here is the model for Gift:
public class Gift {
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public decimal Price { get; set; }
public virtual GiftList GiftList { get; set; }
public virtual ApplicationUser Buyer { get; set; }
}
The problem I am having is that when I go to the edit page and save, I get an error because the Gift that is being passed to Edit() has a null value for GiftList.
The exception that is being thrown:
System.NullReferenceException: Object reference not set to an instance of an object.
At the line:
return RedirectToAction("View", "GiftList", new { id = gift.GiftList.ID });
I tried adding "GiftList" to the Include section of parameters but the gift.GiftList was still null. This is the only area I have a problem with getting the gift.GiftList. I have a feeling this has something to do with what values are edited on the Edit webpage, but I haven't been able to find anything online about this. Is there any way I can easily get the GiftList from the Gift or will I have to do something like db.Gifts.FirstOrDefault(x => x.ID == gift.ID).GiftList
?
Upvotes: 1
Views: 980
Reputation: 16498
If you're not posting GiftList
data to the action method along with the Gift
properties, there's no GiftList
entity to assign to the GiftList
property.
Load the entity from the database, update the properties with the action method parameter's properties, save back to database.
var g = db.Gifts.Find( gift.Id );
if( null == g )
{
// entity not found
}
else
{
g.Name = gift.Name;
// repeat with all editable properties
}
db.SaveChanges();
Upvotes: 1