Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return the current action in an ASP.NET MVC view?

Tags:

c#

asp.net-mvc

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.)?

like image 387
buggs Avatar asked Dec 12 '08 11:12

buggs


People also ask

How do I return a view to action?

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.

Can I return action result instead of view result?

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.

What is the return type of action method in ASP NET MVC?

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.


1 Answers

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 

Update for MVC 3

ViewContext.Controller.ValueProvider.GetValue("action").RawValue ViewContext.Controller.ValueProvider.GetValue("controller").RawValue ViewContext.Controller.ValueProvider.GetValue("id").RawValue 

Update for MVC 4

ViewContext.Controller.RouteData.Values["action"] ViewContext.Controller.RouteData.Values["controller"] ViewContext.Controller.RouteData.Values["id"] 

Update for MVC 4.5

ViewContext.RouteData.Values["action"] ViewContext.RouteData.Values["controller"] ViewContext.RouteData.Values["id"] 
like image 129
Christian Dalager Avatar answered Oct 05 '22 23:10

Christian Dalager