what is the best way to bind ViewModel data to mas

2019-07-26 05:29发布

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

  1. First approach is have a base controller that loads up all shared view model data in its constructor. This is described here

  2. 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?

1条回答
孤傲高冷的网名
2楼-- · 2019-07-26 05:55

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.

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 :-)

查看更多
登录 后发表回答