首页 > 代码库 > MVC3----模型绑定
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="http://www.mamicode.com/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="http://www.mamicode.com/1" />
<input type="text" name="name" value="http://www.mamicode.com/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----模型绑定
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。