[ACCEPTED]-ASP.NET MVC: Access controller instance from view-asp.net-mvc
ViewContext.Controller, and you'll need 16 to cast it.
<% var homeController = ViewContext.Controller as HomeController; %>
This is covered with a few extra 15 wrinkles in post Asp.Net MVC: How do I get virtual url for the current controller/view?.
EDIT: This is to add some 14 meat to Mark Seemann's recommendation that 13 you keep functionality out of the view as 12 much as humanly possible. If you are using 11 the controller to help determine the markup 10 of the rendered page, you may want to use 9 the
Html.RenderAction(actionName, controllerName) method instead. This call will fire 8 the action as though it was a separate request 7 and include its view as part of the main 6 page.
This approach will help to enforce 5 separation-of-concerns because the action 4 method redirected to can do all the heavy 3 lifting with respect to presentation rules. It 2 will need to return a Partial View to work 1 correctly within your parent view.
In my opinion, you should consider a design 17 where the View doesn't need to know about 16 the Controller. The idea is that the Controller 15 deals with the request, conjures up a Model 14 and hands that Model off to the View. At 13 that point, the Controller's work is done.
I 12 think it is an indication of a design flaw 11 if the View needs to know anything about 10 the Controller. Can you share more about 9 what it is that you are trying to accomplish?
I 8 often find that when dealing with well-designed 7 frameworks (such as the MVC framework), if 6 it feels like the framework is fighting 5 you, you are probably going about the task 4 in the wrong way. This has happened to me 3 a lot, and stepping back and asking myself 2 what it is that I'm really trying to accomplish 1 often leads to new insights.
More Related questions