MVC5单击“从详细信息页面删除”

时间:2015-01-30 15:28:40

标签: asp.net-mvc asp.net-mvc-5

我开始使用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>
}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:-1)

您可以通过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
  }
});
}
相关问题