0

How can I get the Viewbag title of the controllers index?

For example, if I am at mysite.com/MyController/MyAction, I would like to render the Viewbag title from the controllers index, being mysite.com/MyController.

The Viewbag title for the index would be "My Controller".

I attempted to get the controller name and render it as a string, although that is not ideal. I did that using the following:

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString())
Fizzix
  • 23,679
  • 38
  • 110
  • 176
  • 1
    i wish i understood what you were asking. How is `ViewBag` tied to anything other than programmer provided values? – T McKeown Feb 18 '15 at 01:34
  • You want to display "My Controller" for all the actions of MyController? Setting the value of ViewBag.title in the constructor of your controller doesn't accomplish what you want? – Augusto Barreto Feb 18 '15 at 01:38
  • @TMcKeown - Sorry mate, first week using C# haha. Usually a PHP developer. I'm creating a basic breadcrumb structure if that helps. Rendering out the Viewbag title of the current action, and I need the controller name to display as the parent. – Fizzix Feb 18 '15 at 01:39

1 Answers1

1

I think you are referring to the Viewbag.title that gets populated in the razor view/C# code block. Viewbag.title or viewbag.ANYTHING is coded in either a controller method or set in the view .cshtml, routing or any other MVC page handling does not set any values in the ViewBag.

You can get to your route values like so:

RouteData route = RouteTable.Routes.GetRouteData(httpContext);
UrlHelper urlHelper = new UrlHelper(new RequestContext(httpContext, route));
var routeValueDictionary = urlHelper.RequestContext.RouteData.Values;

This SO answer was of help too: ASP.NET MVC C# Get controller and action name in class

Community
  • 1
  • 1
T McKeown
  • 12,971
  • 1
  • 25
  • 32
  • At the moment, each view of mine has a `ViewBag.Title` that is being set, such as: `@{ViewBag.Title = "MyAction"}`. If I get the ViewBag title on my page, it will return "MyAction". How can I get "MyController" too? – Fizzix Feb 18 '15 at 01:48
  • you could always add code to the constructor of your controller to set `ViewBag.ControllerName=GetType().Name;` – T McKeown Feb 18 '15 at 01:51