Asp.Net中MVC删除数据技巧


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


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