I am learning MVC 3 with Entity Framework and I have a problem with my delete action result method in my controller. I have two ActionResult methods for delete, one with [HttpPost] for submitting data to the database another for populating the view with correct record based on ID.
My problem is I have a null object in my parameter so When I try to commit a delete transaction it can't see the correct values because I have null object with null values.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DBFirstMVC.Models;
namespace DBFirstMVC.Controllers
{
public class BrandController : Controller
{
// Instantiate model of my database when controller is called
//TestBradEntities db = new DBFirstMVC.Models.TestBradEntities();
//
// GET: /Brand/
public ActionResult Index()
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
return View(db.Brands.ToList());
}
}
//
// GET: /Brand/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Brand/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Brand/Create
[HttpPost]
public ActionResult Create(Brand brand)
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
db.Brands.Add(brand);
db.SaveChanges();
}
return RedirectToAction("Index");
}
//
// GET: /Brand/Edit/5
public ActionResult Edit(int id)
{
try
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
return View(db.Brands.Find(id));
}
}
catch (Exception ex)
{
return View(ex.ToString());
}
}
//
// POST: /Brand/Edit/5
[HttpPost]
public ActionResult Edit(int id, Brand brand)
{
try
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
db.Entry(brand).State = System.Data.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception ex)
{
return View();
}
}
//
// GET: /Brand/Delete/5
public ActionResult Delete(int id)
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
return View(db.Brands.Find(id));
}
}
//
// POST: /Brand/Delete/5
[HttpPost]
public ActionResult Delete(int id, Brand brand)
{
try
{
using (var db = new DBFirstMVC.Models.TestBradEntities1())
{
db.Entry(brand).State = System.Data.EntityState.Deleted;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
This is the code with null object:
[HttpPost]
public ActionResult Delete(int id, Brand brand)
Brand is null and I dont understand why. For example
[HttpPost]
public ActionResult Edit(int id, Brand brand)
Brand Parameter here in Edit actionresult has data in the object and not null values.
Does anyone know how to fix this? Thanks.
What I did to solve this issue was add this line of code:
This seems to find the correct data associated with the ID I passed to the ActionResult method as the int id parameter. I don't understand why Edit actionresult method works but this doesn't but this is an acceptable solution for me.