在 ASP.NET MVC 中应用侧边栏控件逻辑的位置
以希望在 ASP.NET MVC 网站的每个页面上都有一个“最新新闻项目”侧边栏为例。我有一个 NewsItemController,它非常适合专注于 NewsItems 的页面。那么,在主页的 HomeController 上显示新闻侧边栏怎么样?或者任何其他与此相关的控制器?
我的第一反应是将选择前 5 个 NewsItems 的逻辑放入用户控件中,然后在母版页中调用该控件。这样每个页面都会获得一个新闻侧边栏,而不必使用 NewsItem 逻辑污染任何其他控制器。这意味着将逻辑放入我所理解的表示层中,该层通常位于控制器中。
我可以想到大约六种不同的方法来处理它,但就关注点分离和其他相关流行语而言,它们似乎都不“正确”。
Take the example of wanting to have a "Latest news items" sidebar on every page of your ASP.NET MVC web site. I have a NewsItemController which is fine for pages dedicating their attention to NewsItems. What about having a news sidebar appear on the HomeController for the home page though? Or any other controller for that matter?
My first instinct is to put the logic for selecting top 5 NewsItems in a user control which is then called in the Master Page. That way every page gets a news sidebar without having to contaminate any of the other controllers with NewsItem logic. This then means putting logic in what I understood to be the presentation layer which would normally go in a Controller.
I can think of about half a dozen different ways to approach it but none of them seem 'right' in terms of separation of concerns and other related buzz-words.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你应该考虑将其放入你的母版页中。您的控制器可以收集数据(当然是异步的),将其存储在视图的一个漂亮的 ViewModel 属性中(或 TempData 中),然后您可以在母版页中调用 RenderPartial() 来呈现数据。
使一切保持“独立”
I think you should consider putting it in your master page. Your controller can gather data (asynchronously, of course), store it in a nice ViewModel property for your view (or in TempData) and then you can call RenderPartial() in your master page to render the data.
The keeps everything "separate"
http://eduncan911.com/blog/ html-renderaction-for-asp-net-mvc-1-0.aspx
这似乎解决了这个问题 - 即使使用侧边栏的实例 - 但使用默认情况下 MVC 1 不包含的功能。
http://blogs.intesoft.net/ post/2009/02/renderaction-versus-renderpartial-aspnet-mvc.aspx
这也表明答案就在RenderAction中。
对于其他感兴趣的人,这就是我最终的做法。请注意,您需要 MVC Futures 程序集来进行 RenderAction。
基本上你的控制器中会有这样的东西:
然后为 SidebarBox 创建一个部分视图,其中包含你想要显示的内容,并在你的母版页(或任何你想显示它的地方)中使用:
毕竟没那么难。
http://eduncan911.com/blog/html-renderaction-for-asp-net-mvc-1-0.aspx
This seems to address the question - even using the instance of a sidebar - but using a feature not included with MVC 1 by default.
http://blogs.intesoft.net/post/2009/02/renderaction-versus-renderpartial-aspnet-mvc.aspx
This also indicates the answer lies in RenderAction.
For anyone else interested, here's how I ended up doing it. Note you'll need to the MVC Futures assembly for RenderAction.
Basically you'd have something like this in your controller:
Then create a partial view for SidebarBox with the content you want displayed, and in your Master Page (or wherever you want to display it) you'd use:
Not so hard after all.
ASP.NET MVC 新闻部分
News section with ASP.NET MVC