Getting the name of the controller and action method in the view in ASP.Net MVC
Asked Answered
P

2

33

Is there a way in a view in ASP.Net MVC to get the names of the controller and actien method that are using the view?

Porism answered 5/7, 2009 at 9:54 Comment(0)
U
46

Try this:

<%= ViewContext.RouteData.Values["Controller"] %>
<%= ViewContext.RouteData.Values["Action"] %>
Unshroud answered 5/7, 2009 at 9:59 Comment(1)
Those names will reflect the casing of request url. What you do with them should not be case-sensitive. (I fell in that trap.)Genip
R
5
<%= ViewContext.RouteData.Values["Controller"] %>
<%= ViewContext.RouteData.Values["Action"] %>

Be aware that if along the way, your routing has passed through a redirect of some kind, then the those values will still refer to the original requested controller/action, not the "current" one.

So if a request to "/Home/Index" performs a redirect to "/Admin/Settings", then the above values will be "Home" and "Index" respectively and not "Admin" and "Settings" as perhaps may be expected or desired.

Romanaromanas answered 12/10, 2011 at 14:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.