I'm trying to change the default ViewBag.Title for all my controllers, so I though about making a base class that inherit from Controller and handle the title there:
public class MyController : Controller
{
public MyController()
: base()
{
var controller = default(object);
if (RouteData.Values.TryGetValue("controller", out controller))
{
ViewBag.Title = controller;
}
}
}
Then inherit that class from my controllers :
public class GlobalSettingsController : MyController
{
But when I run the page I get a null reference exception because RouteData is null.
How comes it's null? And what can I do?
you are executing the code inside the constructor, before any values is assigned to the controller.
A better place to do this is in OnActionExecuting like this:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
var controller = default(object);
if (RouteData.Values.TryGetValue("controller", out controller))
{
ViewBag.Title = controller;
}
}
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