ASP.NET中MVC傳遞資料的幾種形式總結_實用技巧

來源:互聯網
上載者:User

本文執行個體講述了ASP.NET中MVC傳遞資料的幾種形式。分享給大家供大家參考。具體如下:

在Asp.net mvc開發中,Controller需要向View提供Model,然後View將此Model渲染成HTML。這篇文章介紹三種由Controller向View傳遞資料的方式,實現一個DropDownList的顯示。

第一種:ViewData

ViewData是一個Dictionary。使用非常簡單,看下面代碼:

public ActionResult ViewDataWay(int id){ Book book =bookRepository.GetBook(id); ViewData["Countries"] = new SelectList(PhoneValidator.Countries, book.Country); return View(book);}

在View中使用下面代碼取值:

<div class="editor-field">    <%= Html.DropDownList("Country", ViewData["Countries"] as SelectList) %>    <%: Html.ValidationMessageFor(model => model.Country) %></div>

上面代碼使用as將它轉換成SelectList。

處理POST代碼如下:

[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,代碼如下:

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存放資料的代碼如下:

public ActionResult ViewModelWay(int id){  Book book = bookRepository.GetBook(id);  return View(new BookViewModel(book));}

在View中,這種方式比第一種方式好在:它支援智能感應。

效果和第一種方式一樣。

第三種:TempData

使用TempData和使用ViewData方法是一樣的。

Action代碼如下:

public ActionResult TempDataWay(int id){   Book book = bookRepository.GetBook(id);   TempData["Countries"] = new SelectList(PhoneValidator.Countries, book.Country);   return View(book);}

View取值的代碼如下:

<div class="editor-field">  <%= Html.DropDownList("Country", TempData["Countries"] as SelectList) %>  <%: Html.ValidationMessageFor(model => model.Country) %></div>

效果:第一種方式一樣。

TempData和ViewData的區別

做個簡單的測試看下看下TempData和ViewData的區別

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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.