MVC3----模型绑定
模型绑定(用于获取表单或者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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。