Joe24
Joe24

Reputation: 161

Delete Method based on condition in MVC 4

I have created an application in MVC 4 using Razor HTML. I have set up a model that has a few properties and my delete method which is posted below. This method works perfectly except for the fact that I don't want it to allow me to delete anything if one of the properties is not a certain number. How can i implement that in this method?

public ActionResult Delete(int id = 0)
{
Material material = db.Materials.Find(id);
if(material == null)
{
    return HttpNotFound();
}
return View(material);
}


[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Material material = db.Materials.Find(id);
db.Materials.Remove(material);
db.SaveChanges();
return RedirecttoAction("Index");
}

Upvotes: 0

Views: 3335

Answers (1)

tvanfosson
tvanfosson

Reputation: 532435

In both your get and post actions, check the property and return an alternate "no delete allowed" view if the property you are checking doesn't have an allowable value.

public ActionResult Delete(int id = 0)
{

    Material material = db.Materials.Find(id);
    if(material == null)
    {
        return HttpNotFound();
    }
    else if (material.CheckedProperty != AllowableValue)
    {
        return View("DeleteNotAllowed", material);
    }
    return View(material);
}


[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
    Material material = db.Materials.Find(id);
    if (material.CheckedProperty != AllowableValue)
    {
         return View("DeleteNotAllowed", material);
    }

    db.Materials.Remove(material);
    db.SaveChanges();
    return RedirecttoAction("Index");
}

Upvotes: 2

Related Questions