ViewBag
MVC3中 ViewBag、ViewData和TempData的使用和差別
在MVC3開始。視圖數據能夠通過ViewBag屬性訪問。在MVC2中則是使用ViewData。MVC3中保留了ViewData的使用。ViewBag 是動態類型(dynamic),ViewData 是一個字典型的(Dictionary)。
ViewBag和ViewData的差別:
ViewBag 不再是字典的鍵值對結構。而是 dynamic 動態類型。它會在程序執行的時候動態解析。
所以在視圖中獲取它的數據時候不須要進行類型轉換
| ViewData | ViewBag |
| 它是Key/Value字典集合 | 它是dynamic類型對像 |
| 從Asp.net MVC 1 就有了 | ASP.NET MVC3 才有 |
| 基於Asp.net 3.5 framework | 基於Asp.net 4.0與.net framework |
| ViewData比ViewBag快 | ViewBag比ViewData慢 |
| 在ViewPage中查詢數據時須要轉換合適的類型 | 在ViewPage中查詢數據時不須要類型轉換 |
| 有一些類型轉換代碼 | 可讀性更好 |
Contorller
<pre class="csharp" name="code">using NewOjbect.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace NewOjbect.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.UserName = "無鹽海";
ViewBag.Age = "25";
ViewBag.Gender = 1;
string[] Itmes = new string[] { "中國", "美國", "德國" };
ViewBag.itemsA = Itmes;// viewbag是一個新的dynamic類型keyword的封裝器 //ViewData["Items"] = items;
return View();
}
}
}
View
<pre class="html" name="code"><html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Test2</title>
</head>
<body>
<div>
username:<input type="text" id="UserName" name="UserName" value="@ViewBag.UserName" /></br>
年 齡: <input type="text" id="age" name="age" value=@ViewBag.Age /></br>
性 別:<input type="text" id="Gender" name="Gender" value="@ViewBag.Gender" /></br>
<button>提交</button>
<!---這里輸出國家名-->>
@foreach (dynamic item in ViewBag.itemsA)
{
<p>@item</p>
}
</div>
</body>
</html>
