Validate delete in controller, return html helper

Asked

Viewed 140 times

2

I have my registration, which was done using Scallfold’s visual studio In my view:

   @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-danger" /> |
        </div>
    }

And on my controller:

public ActionResult DeleteConfirmed(string id)
{
    Cliente cliente = db.Clientes.Find(id);
    db.Clientes.Remove(cliente);
    db.SaveChanges();
    return RedirectToAction("Index");
}

How do I validate the deletion if there is already registration with this client? How to return to View using html helper?

1 answer

2


Put in the View:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <div class="form-actions no-color">
        <input type="submit" value="Delete" class="btn btn-danger" /> |
    </div>
}

Controller:

public ActionResult DeleteConfirmed(string id)
{
    Cliente cliente = db.Clientes.Include(c => c.Registros).SingleOrDefault(c => c.Id == id);
    if (cliente.Registros.Count > 0) {
        ModelState.AddModelError("", "Cliente possui registros pendentes.");
        return View("Delete", cliente)
    }

    db.Clientes.Remove(cliente);
    db.SaveChanges();
    return RedirectToAction("Index");
}
  • No error message in view...

  • @Rod You put the @Html.ValidationSummary(true)?

  • I think I told you nonsense. The @Html.ValidationSummary(true) it has to be inside the Html.BeginForm.

  • Exactly this way, does not appear msg in the View, I even tried with Validationmessage("Error") also does not appear

  • @Rod I reviewed some things and the RedirectToAction does not consider the validation result. I updated my answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.