MVC3----模型绑定
模型绑定(用于获取表单或者URL提交的参数)
创新互联主要从事网站设计制作、成都网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务杭锦后,十载网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792
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
匹配表单:
例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); }
匹配表单:
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); }
文章题目:MVC3----模型绑定
地址分享:http://cdiso.cn/article/pjejsp.html