Marcel
Marcel

Reputation: 267

How can I find out the name of the controller action that called my view in MVC3?

I would like to code some logic into my views that depends on the name of the controller action used to call the view. Is there a way I can find out this name.

Hope somebody can help me with that. Please note that it's MVC3 I am using.

Upvotes: 8

Views: 3544

Answers (3)

Robert Greiner
Robert Greiner

Reputation: 29772

Get the name of the controller

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

Get the name of the action

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

I found that here.

Upvotes: 13

Rory McCrossan
Rory McCrossan

Reputation: 337713

@ViewContext.RouteData.Values["Controller"]
@ViewContext.RouteData.Values["Action"]

While this works, I'd suggest it's a little inelegant. Personally I'd add these options as flags to a ViewModel and pass that to my View.

Upvotes: 5

archil
archil

Reputation: 39501

ViewContext.RouteData.Values["action"] may be used, but it is bad choise to let view decide such things. You could use display and editor templates to generate different views and then let action choose its view. Views should be very simple and rely on data that that receive via ViewData or their model. Best to let controller decide such things as differenciate some views with action

Upvotes: 3

Related Questions