ASP.NET MVC:从视图访问控制器实例 [英] ASP.NET MVC: Access controller instance from view

查看:228
本文介绍了ASP.NET MVC:从视图访问控制器实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何从视图访问控制器实例?例如。我有一个的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; %>

这是覆盖着在后<一一些额外的皱纹href="http://stackoverflow.com/questions/151963/asp-net-mvc-how-do-i-get-virtual-url-for-the-current-controller-view">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.

这篇关于ASP.NET MVC:从视图访问控制器实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆