Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 727
Marcel Avatar asked May 16 '11 13:05

Marcel


People also ask

How do you get the name of the current action and controller in the view?

string currentViewName = ((WebFormView)ViewContext. View). ViewPath; You can retrive both physical name of current view and action that triggered it.

How do you go from view to controller?

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.

Does the controller return a view?

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.

Which type of view does not have an associated controller?

New view controllers do not have an associated class initially, so you must assign one using the Identity inspector.


3 Answers

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.

like image 77
Robert Greiner Avatar answered Nov 01 '22 13:11

Robert Greiner


@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.

like image 27
Rory McCrossan Avatar answered Nov 01 '22 14:11

Rory McCrossan


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

like image 24
archil Avatar answered Nov 01 '22 13:11

archil