ASP.NET MVC3中的ViewBag動態性

來源:互聯網
上載者:User

在MVC 3中的有一個新的ViewBag 動態特性,它主要是為了從Controller到view進行傳值用的,類似有所使用的ViewData[] 字典類。對於ViewBag是如此的強大,意味著你能動態set/get  值,增加任何數量的的額外欄位而不需要強型別的檢測。

為了看這些的不同(和不用viewbag的時候),我們來看看一下的執行個體:

Eample:--using ViewBag

Controller

 

public ActionResult Index()   {       List<string> colors = new List<string>();       colors.Add("red");       colors.Add("green");       colors.Add("blue");                      ViewData["listColors"] = colors;       ViewData["dateNow"] = DateTime.Now;       ViewData["name"] = "Hajan";       ViewData["age"] = 25;          return View();   } 

View (ASPX View Engine)

p>  02      My name is  03     <b><%: ViewData["name"] %></b>,   04     <b><%: ViewData["age"] %></b> years old.  05      <br />      06      I like the following colors:  07  </p>  08  <ul id="colors">  09  <% foreach (var color in ViewData["listColors"] as List<string>){ %>  10      <li>  11         <font color="<%: color %>"><%: color %></font>  12     </li>  13  <% } %>  14  </ul>  15  <p>  16      <%: ViewData["dateNow"] %>  17  </p> 


Eample :-Using ViewBag

Controller

public ActionResult Index()  02  {  03      List<string> colors = new List<string>();  04      colors.Add("red");  05      colors.Add("green");  06      colors.Add("blue");  07     08     ViewBag.ListColors = colors; //colors is List  09      ViewBag.DateNow = DateTime.Now;  10      ViewBag.Name = "Hajan";  11      ViewBag.Age = 25;  12      return View();   13 } 


你和上面的對比 你看見了不同嗎。

View (ASPX View Engine)

<p>       My name is      <b><%: ViewBag.Name %></b>,       <b><%: ViewBag.Age %></b> years old.       <br />           I like the following colors:   </p>   <ul id="colors">      <% foreach (var color in ViewBag.ListColors) { %>       <li>           <font color="<%: color %>"><%: color %></font>       </li>   <% } %>      </ul>   <p>       <%: ViewBag.DateNow %>   </p> 


 

在上面的例子以內ViewBag是動態類型的,所以我沒有必要把 ViewBag.ListColors 轉換成如 List<string>這樣子的形式。另一方面,這個ViewData["key"]是一個對方。

如果你在你的Controller中使用ViewData["ListColors"]=Colors,那麼你可以在View試圖中通過ViewBag.ListColors來檢索它們。

 


 

聯繫我們

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