cshtml访问ViewBag对象吗

cshtml访问ViewBag对象吗

本文介绍了为什么不能_ViewStart.cshtml访问ViewBag对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我默认_ViewStart.cshtml在我/浏览文件夹。我想能够访问我的ViewBag对象,以便我可以设置默认标题为我所有的意见。

I have the default _ViewStart.cshtml in my /Views folder. I'd like to be able to access my ViewBag object so I can set the default title for all my views.

然而,随着

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

我得到一个运行时错误'ViewBag'的名称在当前情况下不存在。

I get "The name 'ViewBag' does not exist in the current context" as a runtime error.

我需要做什么呢?

推荐答案

在短...使用控制器的看法袋。

In short... Use the controller's view bag.

ViewContext.Controller.ViewBag.MyVar = "myVal";

@ViewContext.Controller.ViewBag.MyVar

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

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

在这里有很好的信息:

There is good information here: http://forums.asp.net/post/4254825.aspx

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

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

一般情况下,计算机[STORENAME]是一样的ViewBag.StoreName

此外,Controller.ViewData [STORENAME] = Controller.StoreName =
  ViewContext.Controller.ViewBag.StoreName
  = ViewContext.Controller.ViewData [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/

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

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

有一个另一种解决方案在这里:

There is a another solution here: http://stackoverflow.com/a/4834382/291753

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

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

这篇关于为什么不能_ViewStart.cshtml访问ViewBag对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:50