cspyr0
cspyr0

Reputation: 105

MVC5 One Click Delete from Details Page

I started with the scaffolding that VS MVC 5 can create, and it was working fine, but I wanted to be able to delete records ("Interviews", in this case) from the details page.

I started by copying the markup from the delete button on the Delete page over to Details, but it would simply redirect to the Details action. How can I get a button on the Details page to run the DeleteConfirmed method?

Here is the relevant code from the controller:

public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Interview interview = db.Interviews.Find(id);
    if (interview == null)
    {
        return HttpNotFound();
    }
    return View(interview);
}

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    Interview interview = db.Interviews.Find(id);
    db.Interviews.Remove(interview);
    db.SaveChanges();
    return RedirectToAction("Index");
}

public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Interview interview = db.Interviews.Find(id);
    if (interview == null)
    {
        return HttpNotFound();
    }
    return View(interview);
}

and here is the markup that I copied from the Delete page and put into the Details view:

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    <div class="form-actions no-color">
        <input type="submit" value="Delete" class="btn btn-danger" />
    </div>
}

Here is the markup I needed to make it work:

@using (Html.BeginForm("Delete", "Interviews", new { id = Model.ID })) {
    @Html.AntiForgeryToken()
    <div class="form-actions no-color">
        <input type="submit" value="Delete" class="btn btn-danger" />
    </div>
}

Upvotes: 0

Views: 1988

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239290

You need to post to the DeleteConfirm action. Here, you're posting to the Details action because you're using just Html.BeginForm(). You need:

@using (Html.BeginForm("Delete", new { id = Model.Id })) {

Upvotes: 2

M.Azad
M.Azad

Reputation: 3763

You can get delete confirm by javascript on onclickling method like this

//change input type to button to prevent form submit
<input **type="button"** onClick="deleteConfirm" value="Delete" class="btn btn-danger" />
function deleteConfirm()
{
 $.ajax({
  url: "DeleteConfirmed Action Url",
  type:"post", 
  data:{id:} 
  success: function(response) {
    //check your server side result
  }
});
}

Upvotes: -1

Related Questions