[英]ASP.NET MVC: Access controller instance from view
How can I access a controller instance from the view? 如何从视图访问控制器实例? Eg I have a
HomeController
which then returns my Index
view. 例如,我有一个
HomeController
,然后返回我的Index
视图。 Inside of that view I want to access the HomeController
instance that created the view. 在该视图内部,我想访问创建该视图的
HomeController
实例。 How do I do that? 我怎么做?
ViewContext.Controller, and you'll need to cast it. ViewContext.Controller,则需要对其进行强制转换。
<% 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? Asp.Net MVC帖子中对此进行了一些补充说明:如何获取当前控制器/视图的虚拟URL? .
。
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. 编辑 :这是在Mark Seemann的建议中增加一些内容的建议,即您尽可能避免人为地使用功能。 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. 如果使用控制器来帮助确定呈现页面的标记,则可能需要使用
Html.RenderAction(actionName, controllerName)
方法。 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.
它需要返回一个局部视图以在父视图中正常工作。
In my opinion, you should consider a design where the View doesn't need to know about the Controller. 我认为,您应该考虑不需要View知道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. 我认为,如果View需要了解有关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. 我经常发现,在处理设计良好的框架(例如MVC框架)时,如果感觉该框架正在与您抗争,那么您可能会以错误的方式来完成任务。 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.
这在我身上发生了很多事情,退后一步去问自己,我真正想要完成的任务通常会带来新的见解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.