削除リンクをクリックすると、StudentControllerでDeleteConfirmedメソッドを呼び出します。
学生コントローラーコード
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Student student = db.Students.Find(id);
db.Students.Remove(student);
db.SaveChanges();
return RedirectToAction("Index");
}
Index.cshtmlには削除リンク(コードの最後の行)があり、クリックするとDeleteConfirmedが呼び出されますが、以下ではdelete.cshtmlが存在することを想定しています。削除ビューを表示したくないので、削除を実行したいだけです。非同期的に。
@model IEnumerable<SMS.Model.Student>
@{
ViewBag.Title = "Student";
}
<h2>Student</h2>
@using (Html.BeginForm()) {
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.RegistrationNo)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.MiddleName)
</th>
<th>
@Html.DisplayNameFor(model => model.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.DateofBirth)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.RegistrationNo)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.MiddleName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateofBirth)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Ajax.ActionLink("Delete", "Delete", new { id = item.Id },new AjaxOptions { HttpMethod = "Post"})
</td>
</tr>
}
}