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.GetType().Name
, but how do I get the current action (e.g. Index
, Show
etc.)?
To return a view from the controller action method, we can use View() method by passing respective parameters. return View(“ViewName”) – returns the view name specified in the current view folder (view extension name “. cshtml” is not required. return View("~/Views/Account/Register.
So if you are sure that your action method will return some view page, you can use ViewResult. But if your action method may have different behavior, like either render a view or perform a redirection. You can use the more general base class ActionResult as the return type.
In most cases, a controller action returns a ViewResult. For example, the Index controller action in Listing 2 returns a ViewResult. When an action returns a ViewResult, HTML is returned to the browser.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With