gurehbgui gurehbgui - 13 days ago 5
ASP.NET (C#) Question

How to create a BaseController with a ViewBag

I need to do the following:
I have some Controllers ready and running, but now I want to create a

BaseController
.
Each of my
Controllers
should inherit from it like this:

public class MySecondController : BaseController


thats already running so far. Now the Problem:

I want to add a
ViewBag
into this base controller. This
ViewBag
should be accessable from every view which is called in my controllers.

How to realise this?

Answer

You can override OnActionExecuting method in the overridden method you can data to ViewBag dictionary.

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ViewBag.someThing = "someThing"; //Add whatever
        base.OnActionExecuting(filterContext);
    }
}
Comments