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
匹配表单:
例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); }
创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。
文章名称:MVC3----模型绑定-创新互联
链接分享:http://scyanting.com/article/dheijo.html