在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中查询数据时不需要类型转换 |
有一些类型转换代码 | 可读性更好 |
源代码比较中:
ViewBag是:
public dynamic ViewBag {
get {
if (_dynamicViewData == null) {
_dynamicViewData = new DynamicViewDataDictionary(() => ViewData);
}
return _dynamicViewData;
}
}
ViewData是:
public ViewDataDictionary ViewData {
get {
if (_viewData == null) {
SetViewData(new ViewDataDictionary());
}
return _viewData;
}
set {
SetViewData(value);
}
}
Demo例子对比:
View:
<pre class="html" name="code"><html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Test2</title>
</head>
<body>
<div>
用户名:<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>
controller:
<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类型关键字的封装器 //ViewData["Items"] = items;
return View();
}
}
}
贴上原文链接:http://www.cnblogs.com/wintersun/archive/2012/01/21/2328563.html
http://blog.csdn.net/fanbin168/article/details/44803437