雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

ViewData和ViewBag的区别,ViewData和ViewBag哪个更好

2024-10-19 3

ViewData是Key/Value字典集合,从Asp.net MVC 1 就有了,是基于Asp.net 3.5 framework的,ViewData比ViewBag快,在ViewPage中查询数据时需要转换合适的类型。

而ViewBag是dynamic类型对像,是从ASP.NET MVC3 才有的,基于Asp.net 4.0以上,ViewBag比ViewData慢,在ViewPage中查询数据时不需要类型转换,可读性更好。

那在开发过程中,到底用哪个好呢?我个人从面向对象的角度更推荐使用ViewBag,其实他们两个实现的功能都一样。

分别举两个例子说明问题:

例1,ViewData

controller中:

List<int> intList = new List<int>();

intList.Add(1);

intList.Add(2);

ViewData["intList"] = intList;

cshtml中:

@foreach ( var module in ViewData["intList"] as List<int> )

//遍历

 

例2,ViewBag

controller中:

List<int> intList = new List<int>();

intList.Add(1);

intList.Add(2);

ViewBag.intList = intList;

cshtml中:

@foreach ( var module in ViewBag.intList )

//遍历

看了例子大家应该看出区别了吧,虽然之前提到ViewData比ViewBag快,但是我个人还是推荐使用ViewBag。再说了,ORM有ADO.NET快吗?可是实际开发的时候当然还要考虑开发效率,面向对象等等了。

更新于:2小时前
赞一波!

文章评论

评论问答