ASP.NET MVCデータ削除

8060 ワード

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