您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
模型绑定(用于获取表单或者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); }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。