如何从母版页中动态列出现有的操作控制器?
我想列出母版页中的所有现有控制器。
例如:
在我的 Controller 文件夹中,我有:
- HomeController ,带有操作 Index 等...
- ProductController 带有操作 Index、Details 等...
- ServiceController 带有操作 Index、Edit 等...
- SomethingController 带有操作 Index、Update 等。 ..
- 等
在我的 Site.master 中,我想动态列出所有这些操作控制器。
I want to list all the existing controllers from within master page.
For example:
In my Controller folder I have:
- HomeController with actions Index, etc...
- ProductController with actions Index, Details, etc...
- ServiceController with actions Index, Edit, etc...
- SomethingController with actions Index, Update, etc...
- etc
From within my Site.master, I want to list all of these Action controller dynamically.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然我完全同意@Darin的回复,这是一种相对简单的方法来完成您所要求的操作,使用 ViewData。
关于枚举所有控制器的实际逻辑。我不会在这里添加,因为这是一个合理的这样做的方式,我可能无法改进。
您可以使用 ViewData 来执行一些操作,从 OnActionExecuting 动态存储所有控制器和操作。您必须创建一个新控制器,所有其他控制器都将从该控制器继承。
因此,例如,使用您的 ProductController:
...
在您的母版页中...
Whilst I totally agree with @Darin's response, here is a relatively simple way to do what you're asking, using ViewData.
Regarding the actual logic for enumerating all controllers. I won't add that here as this is a reasonable way of doing it, that I probably couldn't improve upon.
You could do something using ViewData to store all of your controllers and actions dynamically from OnActionExecuting. You'd have to create a new controller from which all of your other controllers would inherit.
So, for example, with your ProductController:
...
In your master page...
视图不应该提取数据。它们应该显示控制器传递的数据/模型。因此,在控制器内部,您可以使用反射来列出从控制器派生的所有类型,并将它们传递给视图进行渲染。另一种可能性是使用 HTML 帮助器来完成这项工作。
Views are not supposed to pull data. They are supposed to show data/model passed by a controller. So inside your controller you could use reflection to list all the types deriving from Controller and pass them to the view for rendering. Another possibility is to have an HTML helper that will do the job.