ASP.NET MVC、部分视图和数据
谁能详细说明为什么要在每个操作上定义 ViewData["MenuData"] 来实现动态菜单之类的功能?
我有一个简单的部分视图,它呈现一个菜单,我从母版页中呈现此菜单。这对于来自 ASP.NET WebForms 的我来说很直观,但填充菜单的唯一方法是传递 ViewData["MenuData"],但随后我必须在每个控制器操作中执行此操作。确实感觉有点愚蠢,我每次都必须定义这个视图数据。
就可测试性以及 ASP.NET MVC 风格而言,我应该如何处理这个问题?
Can anyone elaborate on why you'd define ViewData["MenuData"] on every action for something like a dynamic menu?
I have a simple partial view which renders a menu, I render this menu from within a master page. This is intutive for me comming from ASP.NET WebForms, but the only way for me to populate the menu is to pass ViewData["MenuData"], but then I have to do this in every controller action. It does feel a bit stupid, that I would have to define this view data every time.
In terms of testability and what's ASP.NET MVC-ish how should I approach this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种选择是使用
RenderAction
方法,它将调用一个操作(在当前控制器上,或者如果您还提供控制器名称,则该控制器),然后该操作可以为您构建菜单数据,并调用您的 ascx 部分视图:所以在我的母版页上我可以:
然后在我的控制器中:
然后成功找到用户控件
\Views\Shared\BlogArchiveList.ascx
如果您想确保您的操作仅在部分视图的上下文中调用,那么您应该使用
ChildActionOnlyAttribute
来装饰它。这是从“futures”命名空间 Microsoft.Web.Mvc 添加到版本 2 中的 System.Web.Mvc 中的。
Another option is to use the
RenderAction
method instead which will call an action (either on the current controller, or if you supply a controller name as well, that controller), which can then build the menu data for you, and call your ascx partial view:So on my master page I can have:
Then in my controller:
This then successfully finds the user control
\Views\Shared\BlogArchiveList.ascx
If you want to ensure that your action is only ever called in the context of a partial view, then you should decorate it with the
ChildActionOnlyAttribute
.This was added into System.Web.Mvc in version 2 from the "futures" namespace Microsoft.Web.Mvc.
您应该使用一个基本控制器来处理视图模型的重复填充,然后让所有控制器从中派生,
请参见此处 ViewModel 最佳实践
You should use a base controller which handles the repeated population of your view model and then have all your controllers derive from it
see here ViewModel Best Practices