[C#][ASP.NET MVC]MVC CRUD Step by Step
小弟在上一篇介紹SubSonic MVC Scaffold Addin後,不久就收到網友來信
該網友希望再不使用該工具下,實現CRUD操作過程(享受敲擊鍵盤的快感?)
這裡小弟用自己的方法簡單實做,當然如有其他更好的方法還請告知小弟。
Create Model
選擇 ADO.NET EF
選擇相關Table加入後Model顯示如下
Create Control
Create a member of type demotestEntities
Index in Controller
public ActionResult Index()
{
var q = from t in db.HOST
select t;
return View(q);
}
Add View
建立強型別
修改index.aspx
修改Site.Master
Index結果
Details in Controller
public ActionResult Details(Int32 id)
{
HOST t = db.HOST.First(ht => ht.SCN == id);
return View(t);
}
Add View
Details結果
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();
}
}
Add View
Edit結果
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();
}
}
Add View
Create結果
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");
}
Delete結果