ASP.NET MVC:从视图访问控制器实例视图、控制器、实例、ASP

由网友(别妄想@)分享简介:我如何从视图访问控制器实例?例如。我有一个的HomeController 然后返回我的首页视图。在那个鉴于我想访问创建视图的HomeController 实例。我该怎么办呢?How can I access a controller instance from the view? E.g. I have a Home...

我如何从视图访问控制器实例?例如。我有一个的HomeController 然后返回我的首页视图。在那个鉴于我想访问创建视图的HomeController 实例。我该怎么办呢?

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?

推荐答案

ViewContext.Controller,和你需要转换它。

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

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

这是覆盖着在后http://stackoverflow.com/questions/151963/asp-net-mvc-how-do-i-get-virtual-url-for-the-current-controller-view.

修改:这是为了增加一些肉类马克·塞曼的建议您保留的功能出来的观点尽可能力所能及的。如果您使用的控制器,以帮助确定所呈现的页面的标记,你可能想使用 Html.RenderAction(actionName,controllerName)方法来代替。此调用将触发动作,就好像它是一个单独的请求,包括其作为主页的部分观点。

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.

此方法将有助于执行分离的-问题,因为重定向到操作方法可以做所有的繁重相对于presentation规则。这将需要返回一个局部视图父视图中正常工作。

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.

阅读全文

相关推荐

最新文章