Ryan Burnham
Ryan Burnham

Reputation: 2669

Best way to handle a validations before a delete?

I need to be to perform validations during the Delete Action in my controller. Does ASP.net MVC3 have anything to assist with this type of validation? I know you can use the Attributes to handle edit validations but what about deletion?

For example i need to check the state of the entity object and if a certain condition is met they are not allowed to delete. What's the best way to check and display an error

Upvotes: 0

Views: 92

Answers (1)

Yasser Shaikh
Yasser Shaikh

Reputation: 47774

You can have your delete action to be like the following, you can check for your condition by making a call like in the example below the method CanThiBeDeleted() does, if not then you can add an error to the Model State and send it back to the view, where this error message will be displayed.

public ActionResult Delete(string id)
{
    if(!_service.CanThisBeDeleted(id))
    {
        ModelState.AddModelError("", "Sorry this cannot be deleted !");
        return View();
    }

    bool isItemDeleted = false;
    isItemDeleted = _service.DeleteItem(id);

    if(isItemDeleted)
    {
        // if deleted send where you want user to go.
        return RedirectToAction("Index");
    }
    else
    {
        ModelState.AddModelError("", "Delete operation failed.");
        return View();
    }
}

your view can have use @Html.ValidationSummary to display the errors/warnings you want to display.

Upvotes: 1

Related Questions