Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Why can't _ViewStart.cshtml access the ViewBag object?

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.

However, with:

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

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

What do I need to do?

question from:https://stackoverflow.com/questions/6578029/why-cant-viewstart-cshtml-access-the-viewbag-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

and

@ViewContext.Controller.ViewBag.MyVar

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

There is good information here: 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/

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...