I wanted to set a css class in my master page depending on the current controller and action. I can get to the current controller via ViewContext.Controller.GetType().Name, but how do I get the current action? (ie Index, Show etc)
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
Use the ViewContext and look at the RouteData collection to extract both the controller and action elements. But I think setting some data variable that indicates the application context (e.g., "editmode" or "error") rather than controller/action reduces the coupling between your views and controllers.
To get the current Id on a View:
ViewContext.RouteData.Values["id"].ToString()
To get the current controller:
ViewContext.RouteData.Values["controller"].ToString()
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
I know this is an older question, but I saw it and I thought you might be interested in an alternative version than letting your view handle retrieving the data it needs to do it's job.
An easier way in my opinion would be to override the OnActionExecuting method. You are passed the ActionExecutingContext that contains the ActionDescriptor member which you can use to obtain the information you are looking for, which is the ActionName and you can also reach the ControllerDescriptor and it contains the ControllerName.
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
ActionDescriptor actionDescriptor = filterContext.ActionDescriptor;
string actionName = actionDescriptor.ActionName;
string controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
// Now that you have the values, set them somewhere and pass them down with your ViewModel
// This will keep your view cleaner and the controller will take care of everything that the view needs to do it's job.
}
Hope this helps. If anything, at least it will show an alternative for anybody else that comes by your question.
I vote for this 2:
string currentActionName = ViewContext.RouteData.GetRequiredString("action");
and
string currentViewName = ((WebFormView)ViewContext.View).ViewPath;
You can retrive both physical name of current view and action that triggered it. It can be usefull in partial *.acmx pages to determine host container.