gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:26:11 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com