MVC 有条件地显示项目
我有一个显示链接菜单的部分(用户控件)。它存在于我的主页上。如果您是管理员,您应该会看到与其他人不同的菜单。
我的 Member 类中有一个名为:IsAdmin() 的方法。通常,如果某人是管理员,则可以很容易地在部分声明中添加一些逻辑来显示正确的菜单,例如:
<% if (member.IsAdmin()) { %>
但是由于我使用 Ninject 进行依赖项注入,并且如果没有所需的依赖项,我的 Member 类就无法实例化( an IMemberRepository)我不知道如何在我的部分中做到这一点。我知道 Ninject 可以向我的 Controller 类的构造函数提供存储库,但我不知道如何部分地执行此操作。
I have a partial (user control) that shows a menu of links. It lives on my masterpage. If you are an admin, you should see a different menu from others.
I have a method in my Member class called: IsAdmin(). Normally it would be very easy to just put some logic in the partial declaratively to show the right menu if someone is an admin, such as:
<% if (member.IsAdmin()) { %>
But since I am using Ninject for dependency injection and my Member class cannot be instantiated without the required dependencies (an IMemberRepository) I am not sure how to do this in my partial. I know that Ninject can supply a the repository to my Controller class' constructor, but I do not knowhow to do this in a partial.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在我看来,根本不应该使用视图注入,因为它很难通过单元测试进行测试。考虑更改设计并让控制器更改视图模型,并使用视图模型来决定显示什么。
如果您确实想要进行视图注入,MVC3 示例应用程序中有一个示例:
https://github.com/ninject /ninject.web.mvc/tree/master/mvc3/src/SampleApplication/Views/Math
In my opinion view injection should not be used at all because it is hardly testable by unit tests. Consider to change the design and let the controller change the view model instead and use the view model to decide what is shown.
If you really want to do view injection there is an example in the MVC3 sample application:
https://github.com/ninject/ninject.web.mvc/tree/master/mvc3/src/SampleApplication/Views/Math
上周我也遇到了同样的困境,因为我有一个部分为各种视图提供了“顶级位置”列表。
确保控制器注入了必要的服务或存储库,以向部分提供所需的数据,然后将其作为动态 viewdata 属性(在 mvc3 中)传递给视图...
或者,更正式地,将其包含在视图中您的控制器返回的模型。
I was in this same predicament last week, as i have a partial that provides a list of 'top locations' to various views.
Ensure that the controller is injected with the necessary service or repository to provide the partial with the data it requires, then pass it to the view as a dynamic viewdata property (in mvc3)...
Or, more formally, include it in the view model that your controller returns.
我想通了。在我的部分中,我输入了以下内容:
现在我可以执行以下操作:
I figured it out. In my partial I put the following in:
And now I can do the following: