Index.cshtml
@model IEnumerable<MvcExample.Models.Category> <script type="text/javascript"> function Delete(categoryID) { if (confirm("確定要刪除?")) { url = "/Category/Delete"; parameter = { id: categoryID }; $.post(url, parameter, function (data) { alert("刪除成功!"); window.location = "/Category"; }); } } </script> <table> <tr class="title"> <td> 名稱 </td> <td> 操作 </td> </tr> @foreach (var item in Model) { <tr> <td> @item.CategoryName </td> <td> <input type="button" onclick="Delete(@item.CategoryID)" text="刪除"/> </td> </tr> } </table>
CategoryController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.Entity; using MvcExample.Models; namespace MvcExample.Controllers { public class CategoryController : Controller { private MvcExampleContext ctx = new MvcExampleContext(); public ActionResult Index() { return View(ctx.Categories.ToList()); } [HttpPost] public ActionResult Delete(int id) { Category category = ctx.Categories.Find(id); ctx.Categories.Remove(category); ctx.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { ctx.Dispose(); base.Dispose(disposing); } } }