ASP.NET MVC: Access controller instance from view

How can I access a controller instance from the view? E.g. I have a HomeController which then returns my Index view. Inside of that view I want to access the HomeController instance that created the view. How do I do that?


Solution 1:

ViewContext.Controller, and you'll need to cast it.

<% var homeController = ViewContext.Controller as HomeController; %>

This is covered with a few extra wrinkles in post Asp.Net MVC: How do I get virtual url for the current controller/view?.

EDIT: This is to add some meat to Mark Seemann's recommendation that you keep functionality out of the view as much as humanly possible. If you are using the controller to help determine the markup of the rendered page, you may want to use the Html.RenderAction(actionName, controllerName) method instead. This call will fire the action as though it was a separate request and include its view as part of the main page.

This approach will help to enforce separation-of-concerns because the action method redirected to can do all the heavy lifting with respect to presentation rules. It will need to return a Partial View to work correctly within your parent view.

Solution 2:

In my opinion, you should consider a design where the View doesn't need to know about the Controller. The idea is that the Controller deals with the request, conjures up a Model and hands that Model off to the View. At that point, the Controller's work is done.

I think it is an indication of a design flaw if the View needs to know anything about the Controller. Can you share more about what it is that you are trying to accomplish?

I often find that when dealing with well-designed frameworks (such as the MVC framework), if it feels like the framework is fighting you, you are probably going about the task in the wrong way. This has happened to me a lot, and stepping back and asking myself what it is that I'm really trying to accomplish often leads to new insights.