[C#][ASP.NET MVC]MVC CRUD Step by Step

  • 8977
  • 0
  • C#
  • 2009-12-31

[C#][ASP.NET MVC]MVC CRUD Step by Step

小弟在上一篇介紹SubSonic MVC Scaffold Addin後,不久就收到網友來信

該網友希望再不使用該工具下,實現CRUD操作過程(享受敲擊鍵盤的快感?)

這裡小弟用自己的方法簡單實做,當然如有其他更好的方法還請告知小弟。

 

Create Model

選擇 ADO.NET EF

image

image

選擇相關Table加入後Model顯示如下

image

 

Create Control

image

Create a member of type demotestEntities

image

Index in Controller

 


public ActionResult Index()
        {
            var q = from t in db.HOST
                    select t;
            return View(q);
        }

Add View

image

建立強型別

image

修改index.aspx

image

修改Site.Master

image

Index結果

image

Details in Controller


 public ActionResult Details(Int32 id)
        {
            HOST t = db.HOST.First(ht => ht.SCN == id);
            return View(t);
        }

image

Add View

image

Details結果

image

Edit in Controller


public ActionResult Edit(Int32 id)
        {
            HOST t = db.HOST.First(ht => ht.SCN == id);
            return View(t);
        }

        //
        // POST: /Host/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Int32 id, FormCollection collection)
        {
            try
            {
                HOST t = db.HOST.First(ht => ht.SCN == id);
                //設定白名單
                TryUpdateModel(t, new string[] { "HOSTNAME", "MNOTE"}
                   , collection.ToValueProvider());              
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

image

Add View

image

Edit結果

image image

Create in Controller


public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Host/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                var t = new HOST();
                //設定白名單
                TryUpdateModel(t, new string[] { "HOSTNAME", "MNOTE" }
                   , collection.ToValueProvider());
                db.AddToHOST(t);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

image

Add View

image

Create結果

image image

Delete in Controller


public ActionResult Delete(Int32 id)
        {
            HOST t = db.HOST.First(ht => ht.SCN == id);
            db.DeleteObject(t);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

image

Delete結果

image image