Serge
Serge

Reputation: 6692

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?

Upvotes: 5

Views: 3101

Answers (1)

Nickolai Nielsen
Nickolai Nielsen

Reputation: 942

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;
      }
   }

Upvotes: 11

Related Questions