Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Current Action from controller code?

This is very similar to another recent question:

How can I return the current action in an ASP.NET MVC view?

However, I want to get the name of the current action from within controller code.

So within the code of a function that's being called by an Action, I want to get a string of the name of the current Action.

Is this possible?

like image 504
Jonathan Avatar asked Sep 11 '09 02:09

Jonathan


People also ask

Which of the following will help you access the current controller from an ASP.NET MVC 5 view?

I can get to the current controller via ViewContext. Controller. GetType().

What is MVC action result?

An action result is what a controller action returns in response to a browser request. The ASP.NET MVC framework supports several types of action results including: ViewResult - Represents HTML and markup. EmptyResult - Represents no result. RedirectResult - Represents a redirection to a new URL.

Which line of code would return the name of the current controller?

RequestContext. RouteData. Values["controller"]. ToString();


1 Answers

You can access the route data from within your controller class like this:

var actionName = ControllerContext.RouteData.GetRequiredString("action");

Or, if "action" isn't a required part of your route, you can just index into the route data as per usual.

like image 94
Ty. Avatar answered Oct 12 '22 00:10

Ty.