10

is any better way to find controller name from masterpage view in asp.net mvc?

thanks achu.

3 Answers3

34

StackOverflow - Getting the name of the controller and action method in the view in ASP.NET MVC:

<%: ViewContext.RouteData.Values["Controller"] %>
<%: ViewContext.RouteData.Values["Action"] %>
Community
  • 1
  • 1
eu-ge-ne
  • 28,023
  • 6
  • 71
  • 62
  • 2
    Note that `ViewContext.RouteData.Values` is a `RouteValueDictionary` and that the values need to be cast to a string for comparisons, eg `<%=(string)ViewContext.RouteData.Values["Action"] == "Index" ? ...` (and save yourself 10 minutes of pain and wishing you could use RoR or even *gasp* PHP). – Rebecca Scott Nov 24 '10 at 08:51
  • 2
    Why would you cast to a string when you can use the safer .ToString()? – Levi Botelho Oct 05 '12 at 06:28
3

Better than what? The master page should have a ViewContext which allows you to get the RouteData. You should be able to get the name of the controller and action from the RouteData, using the "controller" and "action" keys.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
0

In MVC 4.0 Handle like below.

Controller: @ViewContext.RouteData.Values["Controller"]
Action : @ViewContext.RouteData.Values["Action"]