我有我的/ Views文件夹中的默认_ViewStart.cshtml。我想能够访问我的ViewBag对象,所以我可以设置所有我的视图的默认标题。
但是,用:
@{ Layout = "~/Views/Shared/SiteLayout.cshtml"; ViewBag.Title = "bytecourse - Online Courses in Technology"; }
我得到“名称’ViewBag’在当前上下文中不存在”作为运行时错误。
我需要做什么?
解决方法
简而言之…使用控制器的查看包。
ViewContext.Controller.ViewBag.MyVar = "myVal";
和
@ViewContext.Controller.ViewBag.MyVar
================================================== =============
这里有很好的信息:http://forums.asp.net/post/4254825.aspx
================================================== =============
Generally,ViewData[“StoreName”] is same as ViewBag.StoreName
Also,Controller.ViewData[“StoreName”] = Controller.StoreName =
ViewContext.Controller.ViewBag.StoreName
=ViewContext.Controller.ViewData[“StoreName”]But every view and partial view gets its own instance of viewdata.
07001
================================================== =============
这里有另一个解决方案:http://stackoverflow.com/a/4834382/291753
================================================== =============