MVC5 一键从详细信息页面删除



我从VS MVC 5可以创建的脚手架开始,它工作正常,但我希望能够从详细信息页面中删除记录(在这种情况下为"采访")。

我首先将标记从"删除"页面上的删除按钮复制到"详细信息",但它只会重定向到"详细信息"操作。如何在"详细信息"页上获取一个按钮来运行删除确认方法?

以下是来自控制器的相关代码:

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>
}
您需要

发布到DeleteConfirm操作。在这里,您发布到Details操作,因为您只使用 Html.BeginForm() .你需要:

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

你可以像这样通过javascript在点击方法上获得删除确认

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

最新更新