Get Controller's Action name in View

32,529

RawValue is an object, so RawValue == "..." calls Object.op_Equality, which comparse by reference rather than by value.

Call ViewContext.RouteData.GetRequiredString("action")

Share:
32,529
Darbio
Author by

Darbio

'Senior Enterprise Acrhitect' at the NSW Rural Fire Service, Australia

Updated on July 05, 2022

Comments

  • Darbio
    Darbio almost 2 years

    What is the correct way to get the name of the Action returning the View in MVC3?

    I am using ViewContext.Controller.ValueProvider.GetValue("action").RawValue to return the name of the Action (Method), which is creating the View in MVC3. I return this in a Partial View, which is included in the View returned by the Action.

    It works fine for Index, but, when I try to use it for another method name, it always evaluates to false.

    In the immediate window I get the following results:

    ViewContext.Controller.ValueProvider.GetValue("action").RawValue
    "Edit"
    
    ViewContext.Controller.ValueProvider.GetValue("action").RawValue == "Edit"
    false
    

    Which is highly confusing, because the first statement evaluates to a string with value "Edit", while comparing this to a string "Edit" returns false?

    Bizarre...

  • Darbio
    Darbio over 12 years
    Thanks but this returns RequestContext.RouteData.GetRequiredString("action") An object reference is required for the non-static field, method, or property 'System.Web.Routing.RequestContext.RouteData.get'
  • Tim Schimandle
    Tim Schimandle over 8 years
    I used this to get a page to link to itself in a generic fashion: @Url.Action( ViewContext.RouteData.GetRequiredString("action"), ViewContext.RouteData.GetRequiredString("controller") )
  • SLaks
    SLaks over 8 years
    @Ceekay: Just use Request.Url.