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);
        }
    }
}
展开阅读全文

没有更多推荐了,返回首页