MVC5 一键删除详情页

MVC5 One Click Delete from Details Page

我从 VS MVC 5 可以创建的脚手架开始,它工作正常,但我希望能够从详细信息页面删除记录("Interviews",在本例中)。

我首先将标记从“删除”页面上的删除按钮复制到“详细信息”,但它只会重定向到“详细信息”操作。如何在“详细信息”页面上获得 运行 DeleteConfirmed 方法的按钮?

这里是来自控制器的相关代码:

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);
}

这是我从“删除”页面复制并放入“详细信息”视图的标记:

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

这是我需要让它工作的标记:

@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>
}

您需要 post 进行 DeleteConfirm 操作。在这里,您 post 正在执行 Details 操作,因为您只使用了 Html.BeginForm()。您需要:

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

你可以通过javascript onclickling 方法得到删除确认

//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
  }
});
}