I am using MVC4 and I have a question, rather than declaring ViewBag.MenuLevel=”twostage”; in EACH ActionResult in my controllers can I declare it ONCE for each controller somehow? Right now for example I have lets say 40 ActionResults per controller, this seems silly to have to declare a variable that many times – so I am sure I am missing something simple.
I need to be able to consume it in my View somehow to affect presentation. Thoughts? Models? Kind of new to MVC so be gentle! 😉
Basically I want each section (controller) to display a different background-color on the front-end so I want to print the section/controller to an id in the html so I can control via css.
Cheers.
You are going to have to set the ViewBag data each time, that’s an unavoidable feature of the architecture. However, you can make it a little cleaner in terms of controller code with an attribute applied to the controller.
If you apply that attribute to the controller, you won’t have to explicitly add the ViewBag code for each Action method, as
OnActionExecutingis called automatically for every Action method.