ShaneKm
ShaneKm

Reputation: 21328

MVC get controller in helper class

I need to be able to get a controller name in my custom helper class.

I have the following:

  1. Layout view which calls a controller: "HelperController", action: "Menu" like so:

@Html.Action("Menu", "Helper")

  1. This calls ActionResult and generages an html:

    @model List<MvcMenuItem>
    @{
    Layout = null;
    }
    @{        
    @Html.Menu(this.ViewContext).ClientId("navMain").AddRange(Model).Render()
    }
    
  2. This calls "public static class MvcMenuExtensions" and in there (in my Render() method) I need to be able to get the controller name I'm currently in, NOT the controller name that is calling MvcMenuExtensions

I've tried this:

string controller = this.ViewContext.RouteData.Values["controller"].ToString();

but this results in controller being "Helper" controller and not the current controller I'm in. Since this "ActionResult" is being called from anywhere on the page (it's in the layout).

Thanks

Upvotes: 1

Views: 1831

Answers (1)

ShaneKm
ShaneKm

Reputation: 21328

answered here: How to get current controller and action from inside Child action? by juhan_h

ControllerContext.ParentActionViewContext.RouteData.Values["action"] 

OR

ViewContext.ParentActionViewContext.RouteData.Values["action"]

Upvotes: 1

Related Questions