Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current controller & action from within partial view

I'm using the following to get the current controller and action in asp.net MVC3:

var currentAction = routeData.GetRequiredString("action");
var currentController = routeData.GetRequiredString("controller");

This works perfectly. However, if I call this from within a partial view that is called from my layout, "Layout" is returned as the current controller. This is of course correct behaviour, but is there any way to access the parent controller's name?

Edit for further clarification:

I am calling my menu controller and partial view from within _Layout.cshtml:

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

Then from within that Menu partial view, I am calling code which returns the current action and controller.

like image 206
Jonathan Avatar asked Jun 18 '11 18:06

Jonathan


People also ask

How can I get controller in MVC?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add.

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

ToString(); And this will return the name of the controller requested in the URL: var requestedController = HttpContext.

What is ControllerContext MVC?

ControllerContext(ControllerContext) Initializes a new instance of the ControllerContext class by using the specified controller context. ControllerContext(HttpContextBase, RouteData, ControllerBase)

Can we override filters in MVC?

ASP.NET MVC 5 has arrived with a very important feature called Filter Overrides. Using the Filter Overrides feature, we can exclude a specific action method or controller from the global filter or controller level filter. ASP.NET MVC 5 has arrived with a very important feature called Filter Overrides.


2 Answers

After your updated question and showing your code it is much more clear: you are not including a partial view. You are calling a child action. There's a huge difference between Html.Partial and Html.Action. So if you want to get the parent context inside this child action you could do this:

public ActionResult Menu()
{
    var rd = ControllerContext.ParentActionViewContext.RouteData;
    var currentAction = rd.GetRequiredString("action");
    var currentController = rd.GetRequiredString("controller");
    ...
    return View();
}
like image 174
Darin Dimitrov Avatar answered Oct 24 '22 14:10

Darin Dimitrov


I stumbled on this page looking for a way to access the parent controllers name after a call using Partial

@Html.Partial("Paging")

This can be done in the partial view as

@{
    var controller = ViewContext.RouteData.GetRequiredString("controller");
    var action = ViewContext.RouteData.GetRequiredString("action");
}
like image 27
Tom Avatar answered Oct 24 '22 12:10

Tom