ViewData 与 ViewBag

ViewData vs ViewBag

我在其中一篇博客中读到

For ViewData while enumerating type conversion is required but ViewBag since it is dynamic type conversion is not required

但是我们常说ViewBag是对ViewData的封装,所以how/why在类型转换的时候就不一样了?

ViewBag 确实是对ViewData 的包装,从源码可以看出:https://github.com/aspnet/AspNetWebStack/blob/62d0b2df0bcca848a8e0848fd1866928df15528e/src/System.Web.Mvc/ViewPage.cs。在这两种情况下,该值都不是强类型的,因此您需要在使用它之前对其进行转换,除非您想将其用作对象。