MVC對資料庫作CRUD-Edit、Delete

 

經由上一篇MVC對資料庫作CRUD-Create已經實作的Read與Create功能之後,剩下Edite與delete

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyGuestBook2.Models;
using System.Data.Entity;//for DbSet、EntityState to used

namespace MyGuestBook2.Controllers
{
    public class HomeController : Controller
    {
        //宣告GuestBookModels 並與GuestBook資料庫連線
        GuestBookModels mo = new GuestBookModels();

        public ActionResult Index()
        {
            //將這個型別為DbSet的MyEntities做ToList(集合)傳給View
            return View(mo.MyEntities.ToList());
        }

        //導到Create頁面
        public ActionResult Create()
        {
            return View();
        }

        //Create資料
        [HttpPost] //從View表單接收為GuestBook型別的輸入參數
        public ActionResult Create(GuestBookEntity GuestBookEntity)
        {
            //將資料寫進DB
            if (ModelState.IsValid)
            {
                //mo.MyEntities.Add(GuestBookEntity);作用等於mo.Entry(GuestBookEntity).State = EntityState.Added;
                mo.Entry(GuestBookEntity).State = EntityState.Added;

                mo.SaveChanges();
                return RedirectToAction("Index");
            }
            //如果Create失敗則傳回該筆GuestBookEntity型別的物件
            return View(GuestBookEntity);
        }

        //導到Edit頁面
        public ActionResult Edit(int id)
        {
            var GuestBookEntity = from p in mo.MyEntities where p.Id == id select p;
            return View(GuestBookEntity.FirstOrDefault());//回傳該筆GuestBookEntity型別的物件
        }

        //Edit資料
        [HttpPost]
        public ActionResult Edit(GuestBookEntity GuestBookEntity)
        {
            if (ModelState.IsValid)
            {
                mo.Entry(GuestBookEntity).State = System.Data.Entity.EntityState.Modified;
                mo.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(GuestBookEntity);
        }

        //Delete
        public ActionResult Delete(int id)
        {
            //DbSet moEntity = mo.MyEntities;
            //IEnumerable c = from p in moEntity where p.Id == id select p;
            //mo.MyEntities.Remove(c.FirstOrDefault());
            var m = mo.MyEntities.Find(id);
            mo.Entry(m).State = EntityState.Deleted;
            //以上為兩種刪除方式,作用相同

            mo.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}

主要實作重點為Controller與View

完成執行畫面如下

Alternate Text

心得:CRUD算是最基礎的實作,但要深入的話還有很多地方可玩,

可参考我的程式註解,其實還有很多細節要注意的。

程式碼