Main.Controllers.CategoriesController.Delete C# (CSharp) Method

Delete() public method

public Delete ( int id ) : System.Web.Mvc.ActionResult
id int
return System.Web.Mvc.ActionResult
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Category category = db.Categories.Find(id);
            if (category == null)
            {
                return HttpNotFound();
            }

            // don't allow the category to be deleted if its being used
            int postsWithCategory = db.Posts.Where(p => p.CategoryID == category.CategoryID).Count();
            if (postsWithCategory > 0)
            {
                string plural = "";
                if (postsWithCategory > 1) {
                    plural = "s";
                }

                ModelState.AddModelError(String.Empty,
                        "This category has " + postsWithCategory + " post" + plural + " associated with it, please change those postings before deleting category");
            }

            return View(category);
        }

Usage Example

 public void testDelete()
 {
     CategoriesController categoriesController = new CategoriesController();
     ActionResult delete = categoriesController.Delete(5);
 }