How do I know the name of the controller action that triggered my view in MVC3?

I would like to encode some logic in my views, which depends on the name of the controller action used to invoke the view. Is there any way to find out this name.

Hope someone can help me. Please note that this is the MVC3 that I am using.

+8
asp.net-mvc asp.net-mvc-3
source share
3 answers

Get controller name

@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue 

Get action name

 @ViewContext.Controller.ValueProvider.GetValue("action").RawValue 

I found that here .

+12
source share
 @ViewContext.RouteData.Values["Controller"] @ViewContext.RouteData.Values["Action"] 

While this works, I suggest it is a little inelegant. Personally, I would add these parameters as flags in the ViewModel and pass them into my view.

+5
source share

ViewContext.RouteData.Values["action"] may be used, but it is a poor choice to view such solutions. You can use the display and editor templates to create different views, and then let the action select its view. Views should be very simple and rely on the data that is received through ViewData or their model. It’s best to let the controller decide things like the difference between some kinds of actions

+3
source share

All Articles