asp.net MVC-- viewbag和viewdata的区别

在MVC3开始,视图数据可以通过ViewBag属性访问,在MVC2中则是使用ViewData。MVC3中保留了ViewData的使用。ViewBag 是动态类型(dynamic),ViewData 是一个字典型的(Dictionary)。

ViewBag和ViewData的区别:
ViewBag 不再是字典的键值对结构,而是 dynamic 动态类型,它会在程序运行的时候动态解析。所以在视图中获取它的数据时候不需要进行类型转换

ViewDataViewBag
它是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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值