Based upon this post Make a Global ViewBag, I'm trying to implement the following in ASP.NET Core 2.2. I realize the original post was for MVC 3.
public class CompanyFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ViewBag.Company = "MyCompany";
}
}
I'm unable to find in what namespace filterContext.Controller.ViewBag would be defined. Is this still available in ASP.NET Core?
In ASP.NET Core, it's possible to define a controller class that does not inherit from either Controller
or ControllerBase
. Because of this, filterContext.Controller
in your example is of type object
instead of Controller
. However, if the controller is actually an instance of Controller
, you can just cast the Controller
property and then use ViewBag
accordingly. Here's an example:
if (filterContext.Controller is Controller controller)
controller.ViewBag.Company = "MyCompany";
The use of is
here is an example of pattern matching that was introduced in C# 7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With