asp.net-mvc-3 – 为什么_ViewStart.cshtml访问ViewBag对象?

我有我的/ 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

================================================== =============

相关文章

判断URL文件是不是在于在。private static bool UrlIsExist(...
由于在.net中,Request时出现有HTML或Javascript等字符串时,...
public static bool ProcessIdCard(this string idCard, out...
protected void Page_Load(object sender, EventArgs e){ Sc...