本文實例講述了ASP.NET中MVC傳遞數據的幾種形式。分享給大家供大家參考。具體如下:
在Asp.net mvc開發中,Controller需要向View提供Model,然后View將此Model渲染成HTML。這篇文章介紹三種由Controller向View傳遞數據的方式,實現一個DropDownList的顯示。
第一種:ViewData
ViewData是一個Dictionary。使用非常簡單,看下面代碼:
1
2
3
4
5
6
|
public ActionResult ViewDataWay( int id) { Book book =bookRepository.GetBook(id); ViewData[ "Countries" ] = new SelectList(PhoneValidator.Countries, book.Country); return View(book); } |
在View中使用下面代碼取值:
1
2
3
4
|
<div class = "editor-field" > <%= Html.DropDownList( "Country" , ViewData[ "Countries" ] as SelectList) %> <%: Html.ValidationMessageFor(model => model.Country) %> </div> |
上面代碼使用as將它轉換成SelectList。
處理POST代碼如下:
1
2
3
4
5
6
7
8
|
[HttpPost] public ActionResult ViewDataWay( int id, FormCollection collection) { Book book = bookRepository.GetBook(id); UpdateModel<Book>(book); bookRepository.Save(book); return RedirectToAction( "Details" , new { id=id}); } |
第二種:ViewModel
使用ViewModel的方式,我們先創建一個BookViewModel,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class BookViewModel { public Book Book { get ; set ; } public SelectList Countries { get ; set ; } public BookViewModel(Book book) { Book = book; Countries = new SelectList(PhoneValidator.Countries,book.Country); } } |
在控制器的Aciton使用ViewModel存放數據的代碼如下:
1
2
3
4
5
|
public ActionResult ViewModelWay( int id) { Book book = bookRepository.GetBook(id); return View( new BookViewModel(book)); } |
在View中,這種方式比第一種方式好在:它支持智能感應。
效果和第一種方式一樣。
第三種:TempData
使用TempData和使用ViewData方法是一樣的。
Action代碼如下:
1
2
3
4
5
6
|
public ActionResult TempDataWay( int id) { Book book = bookRepository.GetBook(id); TempData[ "Countries" ] = new SelectList(PhoneValidator.Countries, book.Country); return View(book); } |
View取值的代碼如下:
1
2
3
4
|
<div class = "editor-field" > <%= Html.DropDownList( "Country" , TempData[ "Countries" ] as SelectList) %> <%: Html.ValidationMessageFor(model => model.Country) %> </div> |
效果:第一種方式一樣。
TempData和ViewData的區別
做個簡單的測試看下看下TempData和ViewData的區別
1
2
3
4
5
6
7
8
9
10
11
12
|
public ActionResult Test1() { TempData[ "text" ] = "1-2-3" ; ViewData[ "text" ] = "1-2-3" ; return RedirectToAction( "Test2" ); } public ActionResult Test2() { string text1 = TempData[ "text" ] as string ; string text2 = ViewData[ "text" ] as string ; return View(); } |
RedirectToAction跳轉Action后,ViewData的值已經被清空,而TempData沒有被清空,這是它們的區別之一。
希望本文所述對大家的asp.net程序設計有所幫助。