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.
string currentViewName = ((WebFormView)ViewContext. View). ViewPath; You can retrive both physical name of current view and action that triggered it.
ViewBag is a very well known way to pass the data from Controller to View & even View to View. ViewBag uses the dynamic feature that was added in C# 4.0. We can say ViewBag=ViewData + Dynamic wrapper around the ViewData dictionary.
A controller action might return a view. However, a controller action might perform some other type of action such as redirecting you to another controller action.
New view controllers do not have an associated class initially, so you must assign one using the Identity inspector.
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
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