以下的例子以留言本作为依据。
1.添加
public ActionResult Create()
{
return View();
} //
// POST: /Contact/Create [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Message message)
{
if (ModelState.IsValid)
{
db.Messages.Add(message);
db.SaveChanges();
return RedirectToAction("Index");
} return View(message);
}
2.查看
public ActionResult Index()
{
return View(db.Messages.ToList());
}
3.全部更新
//
// GET: /Contact/Edit/5 public ActionResult Edit(int id = )
{
Message message = db.Messages.Find(id);
if (message == null)
{
return HttpNotFound();
}
return View(message);
} //
// POST: /Contact/Edit/5 [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Message message)
{
if (ModelState.IsValid)
{
db.Entry(message).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(message);
}
4.删除
//
// GET: /Contact/Delete/5 public ActionResult Delete(int id = )
{
Message message = db.Messages.Find(id);
if (message == null)
{
return HttpNotFound();
}
return View(message);
} //
// POST: /Contact/Delete/5 [HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Message message = db.Messages.Find(id);
db.Messages.Remove(message);
db.SaveChanges();
return RedirectToAction("Index");
}
5.释放空间
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
6.部分更新记录
有的时候并不需要把一条数据记录全部更新,这时候必须注意编辑数据提交到数据库,会不会让数据库已有数据丢失。下面讨论避免的三种办法。
(1)在表单中利用HiddenFor把值传递到控制器动作中
...
@using(Html.BeginForm())
{
....
@Html.HiddenFor(a=>a.Id)
}
(2)另一种是在控制器中补充完整数据库中的数据。
[HttpPost]
public ActionResult TestForm(Guestbook guestbook)
{
if (ModelState.IsValid)
{
var gb = db.Guestbooks.Find();
gb.confirm=guestbook.confirm;
gb.replied=guestbook.replied;
....
db.SaveChanges();
return Redirect("/");
}
return View();
}
(3)TryUpdateModel
[HttpPost]
public ActionResult TestForm(FormCollection form)
{
if (ModelState.IsValid)
{
var gb = db.Guestbooks.Find();
TryUpdateModel(gb, "", form.AllKeys);
db.SaveChanges();
return Redirect("/");
}
return View();
}
关于TryUpdateModel的用法,还可以是TryUpdateModel(model, new string[] { “字段1”, “字段2”, “字段3” }),以及设置排除form表单接收进来的某些字段TryUpdateModel(model, “”, FromValue.AllKeys, new string[] { “字段1” })。
7.注销
public ActionResult LogOff()
{
//清除窗体验证的Cookies
FormsAuthentication.SignOut(); //清除所有曾经写入过的Session信息
Session.Clear(); return RedirectToAction("Login", "Account");
}