How to create a BaseController with a ViewBag

前端 未结 1 1672
迷失自我
迷失自我 2021-02-18 23:10

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

1条回答
  •  难免孤独
    2021-02-18 23:55

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

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

    Updated for .net Core 2019:

    using Microsoft.AspNetCore.Mvc.Filters;
    
    public abstract class BaseController : Controller
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ViewBag.someThing = "someThing"; //Add whatever
            ViewData["someThingElse"] = "this works too";
            TempData["anotherThing"] = "as does this";
            base.OnActionExecuting(filterContext);
        }
    }
    

    0 讨论(0)
提交回复
热议问题