Model binding (used to get the parameters of a form or URL submission)
1, basic model binding (you can get the parameters of a form submission directly in a parameter using a string, integer variable, entity, or list< entity >)
Example 1:
Public ViewResult Details (int id) {Album Album = db. Album.find (ID); Return View (album);}
Match URL:
Http://localhost/Home/Details/1
Http://localhost/Home/Details?Id=1
Match form:
<input type= "text" name= "id" value= "1"/>
Example 2:
[Httppost]public actionresult Create (Album Album) {if (modelstate.isvalid) {db. Album.add (Album);d B. 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);}
Match form:
<input type= "text" name= "id" value= "1"/>
<input type= "text" name= "name" value= "Tom"/>
2, show model bindings (both Updatemodel and TryUpdateModel are used to display model bindings)
Updatemodel: If an error occurs during binding, an exception is thrown
[Httppost]public actionresult Edit () {Album Album = new Album (); try {Updatemodel (album);d B. 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: Does not throw an exception, it returns a bool value, true for bind success, FALSE for bind failure
[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, Model State
[Httppost]public actionresult Create (Album Album) {if (modelstate.isvalid)//model state {db. Album.add (Album);d B. 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);}
This article is from the "program Ape's Home--hunter" blog, please be sure to keep this source http://962410314.blog.51cto.com/7563109/1585344
MVC3----Model Bindings