I wanted to set a CSS class in my master page, which depends on the current controller and action. I can get to the current controller via ViewContext.Controller.GetTy
To get the current Id on a View:
ViewContext.RouteData.Values["id"].ToString()
To get the current controller:
ViewContext.RouteData.Values["controller"].ToString()
Override this function in your controller
protected override void HandleUnknownAction(string actionName)
{ TempData["actionName"] = actionName;
View("urViewName").ExecuteResult(this.ControllerContext);
}
You can get these data from RouteData of a ViewContext
ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["action"]
In the RC you can also extract route data like the action method name like this
ViewContext.Controller.ValueProvider["action"].RawValue
ViewContext.Controller.ValueProvider["controller"].RawValue
ViewContext.Controller.ValueProvider["id"].RawValue
ViewContext.Controller.ValueProvider.GetValue("action").RawValue
ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
ViewContext.Controller.ValueProvider.GetValue("id").RawValue
ViewContext.Controller.RouteData.Values["action"]
ViewContext.Controller.RouteData.Values["controller"]
ViewContext.Controller.RouteData.Values["id"]
ViewContext.RouteData.Values["action"]
ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["id"]
I am using ASP.NET MVC 4, and this what worked for me:
ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue
ControllerContext.Controller.ValueProvider.GetValue("action").RawValue
In MVC you should provide the View with all data, not let the View collect its own data so what you can do is to set the CSS class in your controller action.
ViewData["CssClass"] = "bold";
and pick out this value from your ViewData in your View