Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Why is RouteData null?

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?

like image 779
Serge Avatar asked Oct 23 '13 08:10

Serge


1 Answers

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;
      }
   }
like image 165
Nickolai Nielsen Avatar answered Oct 05 '22 21:10

Nickolai Nielsen