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.
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.
@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.
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
精彩评论