Asp.Net中MVC删除数据技巧


Index.cshtml页面 



01@model IEnumerable<MvcExample.Models.Category>
02<script type="text/javascript">
03    function Delete(categoryID) {
04        if (confirm("确定要删除?")) {
05            url = "/Category/Delete";
06            parameter = { id: categoryID };
07            $.post(url, parameter, function (data) {
08                alert("删除成功!");
09                window.location = "/Category";
10            });
11        }
12    }
13</script>
14<table>
15    <tr class="title">
16        <td>
17            名称
18        </td>
19        <td>
20            操作
21        </td>
22    </tr>
23    @foreach (var item in Model)
24    {
25        <tr>
26            <td>
27                @item.CategoryName
28            </td>
29            <td>
30                <input type="button" onclick="Delete(@item.CategoryID)" text="删除"/>
31            </td>
32        </tr>
33    }
34</table>
CategoryController.cs 控制器




01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Web;
05using System.Web.Mvc;
06 
07using System.Data.Entity;
08 
09using MvcExample.Models;
10 
11namespace MvcExample.Controllers
12{
13    public class CategoryController : Controller
14    {
15        private MvcExampleContext ctx = new MvcExampleContext();
16 
17        public ActionResult Index()
18        {
19            return View(ctx.Categories.ToList());
20        }
21 
22        [HttpPost]
23        public ActionResult Delete(int id)
24        {
25            Category category = ctx.Categories.Find(id);
26            ctx.Categories.Remove(category);
27            ctx.SaveChanges();
28            return RedirectToAction("Index");
29        }
30 
31        protected override void Dispose(bool disposing)
32        {
33            ctx.Dispose();
34            base.Dispose(disposing);
35        }
36    }
37}


原文链接:Asp.Net中MVC删除数据技巧