標籤:模型繫結 updatemodel tryupdatemodel
模型繫結(用於擷取表單或者URL提交的參數)
1,基本模型繫結(你可以直接在參數中用字串,整型變數,實體或者是List<實體>的方式擷取表單提交的參數)
例1:
public ViewResult Details(int id){ Album album = db.Album.Find(id); return View(album);}
匹配URL:
http://localhost/Home/Details/1
http://localhost/Home/Details?Id=1
匹配表單:
<input type="text" name="id" value="1" />
例2:
[HttpPost]public ActionResult Create(Album album){ if (ModelState.IsValid) {db.Album.Add(album);db.SaveChanges();return RedirectToAction("Index"); } ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId); ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId); return View(album);}
匹配表單:
<input type="text" name="id" value="1" />
<input type="text" name="name" value="tom" />
2,顯示模型繫結(UpdateModel與TryUpdateModel都用於顯示模型繫結)
UpdateModel:如果綁定期間出現錯誤,則會拋出異常
[HttpPost]public ActionResult Edit(){ Album album = new Album(); try {UpdateModel(album);db.Entry(album).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("Index"); } catch{ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);return View(album); }}
TryUpdateModel:不會拋出異常,它會返回一個bool值,true為綁定成功,false為綁定失敗
[HttpPost]public ActionResult Edit(){ Album album = new Album(); if (TryUpdateModel(album)) {db.Entry(album).State = EntityState.Modified;db.SaveChanges();return RedirectToAction("Index"); } ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId); ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId); return View(album);}
3,模型狀態
[HttpPost]public ActionResult Create(Album album){ if (ModelState.IsValid)//模型狀態 {db.Album.Add(album);db.SaveChanges();return RedirectToAction("Index"); } ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId); ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId); return View(album);}
本文出自 “程式猿的家--Hunter” 部落格,請務必保留此出處http://962410314.blog.51cto.com/7563109/1585344
MVC3----模型繫結