Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 634
mmcdole Avatar asked Jul 05 '11 04:07

mmcdole


People also ask

How does _ViewStart Cshtml work?

The _ViewStart. cshtml page is a special view page containing the statement declaration to include the Layout page. Instead of declaring the Layout page in every view page, we can use the _ViewStart page. When a View Page Start is running, the “_ViewStart.

What is ViewBag in Cshtml?

ASP.NET MVC - ViewBag. The ViewBag in ASP.NET MVC is used to transfer temporary data (which is not included in the model) from the controller to the view. Internally, it is a dynamic type property of the ControllerBase class which is the base class of the Controller class.

Can we use ViewBag in Layout page?

Simply use the viewbag in your home controller and you can also access it on the Layout page too.

Can we use ViewBag to pass data from view to controller?

ViewBag itself cannot be used to send data from View to Controller and hence we need to make use of Form and Hidden Field in order to pass data from View to Controller in ASP.Net MVC Razor.


1 Answers

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

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

like image 137
Malgaur Avatar answered Oct 02 '22 07:10

Malgaur