什么是绑定在asp.net MVC的视图模型数据,以母版页的最佳途径

问题描述:

我想我的母版页上动态创建我的菜单,我已经看到了两种不同的方式:

I want to dynamically create my menu on my master page and i have seen 2 different approaches:


  1. 第一种方法是有一个在其构造函数加载了所有共享视图模型数据的基本控制器。 这是这里描述

第二种方法是为此创建一个单独的控制器,并在你的母版页使用此注入特定视图块放入母版页不污染常规页面视图生成:

Second approach is to create a separate controller for this and use this in your master page to inject specific view pieces into the master page without polluting your regular page view generation:

@Html.Action("Index", "Settings")


时比另一个好?是否有任何的最佳做法吗?

Is one better than the other? Is there any best practice here?

我个人preFER第二种方法,因为它允许从主逻辑独立处理菜单。通过使用孩子的行为,你可以有菜单控制器的完全独立的生命周期,而无需对使用该母版绝对是所有视图基本视图模型。继承只是看起来不适合这个情况,但当然,这并不意味着你应该排除这种可能性完全。每一个场景是具体的,取决于具体的细节(你有没有为你提供),可能有不同的做法。

Personally I prefer the second approach as it allows to handle the menu independently from the main logic. By using child actions you could have an entirely separate lifecycle of the menu controller without the need to have a base view model for absolutely all views that use this masterpage. Inheritance just doesn't seem right for this situation but of course this doesn't mean that you should rule it out completely. Every scenario is specific and depending on the exact details (which you haven't provided for yours) there might different approaches.

只是不认为如果 Html.Action 是良好的一个场景,将有利于所有的人。可能有一些项目的具*约因素做出不适当的或者是通过其他的方式实现这一目标。

Just don't think that if Html.Action is good for one scenario it will be good for all of them. There might be some project specific constraints which make inappropriate or maybe achieve this by some other approach.

有没有通用的解决方案,将在所有情况下工作。否则,就不会有一个需要程序员: - )

There is no universal solution that will work in all situations. Otherwise there wouldn't be a need for programmers :-)