MVC3----模型繫結

來源:互聯網
上載者:User

標籤:模型繫結   updatemodel   tryupdatemodel   

模型繫結(用於擷取表單或者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

MVC3----模型繫結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.