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

标签 asp.net-mvc-3 razor

我的/Views 文件夹中有默认的 _ViewStart.cshtml。我希望能够访问我的 ViewBag 对象,以便我可以为所有 View 设置默认标题。

但是,与:

@{
    Layout = "~/Views/Shared/SiteLayout.cshtml";
    ViewBag.Title = "bytecourse - Online Courses in Technology";
}

我收到“当前上下文中不存在名称‘ViewBag’”作为运行时错误。

我需要做什么?

最佳答案

简而言之...使用 Controller 的 View 包。

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.

http://jeffreypalermo.com/blog/viewdata-mechanics-and-segmentation-excerpt-from-asp.net-mvc-in-action/



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

这里有另一个解决方案:https://stackoverflow.com/a/4834382/291753

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

关于asp.net-mvc-3 - 为什么_ViewStart.cshtml不能访问ViewBag对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6578029/

相关文章:

javascript - 更改文本框 onchange 下拉列表的输入类

css - 使用 Razor 将 CSS 转换为样式元素

javascript - 如何将不属于模型一部分的 div 值传递给后端 Controller 方法

c# - 具有多个参数的自定义验证属性

asp.net-mvc - 为什么在构建时, Razor 编译错误不会出现在VS2012中,并且可以解决吗?

c# - 使用 Html.Action() 时,PartialView ViewBag 数据在父 View 中不可用

c# - 数据注释 - DisplayFormat - 格式化数字字符串

c# - 绑定(bind)对象永远不会为空

c# - 输入显示空白而不是零

asp.net-mvc-3 - 跨2个服务层共享方法