开发者

Viewmodel and dynamic menu best practices - ASP.NET MVC

I'm starting a new website in asp.net MVC with a dynamic menu that change depending on the user. But that's not all. I use 2 different layouts (Razor layouts) depending on the user and the 2 differents layouts have a different menu. So I hav开发者_运维百科e 2 different Layouts with 2 different dynamics menus.

I would like to use the same view for the 2 layouts with one viewmodel per view. I use an action filter to determine the layout. Is it a good idea to design a "ViewModel" base class that contain the data to display both menus (even if just one menu is created every time) and create child of this base class for all my viewmodel (one viewmodel per view).

I want to know if it's a good practice. Is it a case where I should use 2 view (one per layout) and use partial views for the common part ?

And if there is some differences on what I want to display on the view depending of the layout, should I use 2 Views instead of one ?

Any recommandations ?


In my opinion, the best practice would be to have one view model for your view, with a property on it containing some object that determines how your dynamic menu is formed. Example:

public class MyViewModel
{
     public int SomeData { get; set; } // basic Stuff
     public IDynamicMenuData MenuData { get; set; }
}

You assign an implementation of dynamic menu data to your view model based on which menu you want to render for that user. Then, in your view you can invoke:

@Html.DisplayFor(x => x.MenuData)

Where you want your dynamic menu. You can then create a display template for each type of IDynamicMenuData implementation, and it will render accordingly. Then, you only need one view, one view model and you can have X number of implementations of your dynamic menu.


I would strongly recommend against using a base view model with menu properties in it because it is very rigid. (What happens if you use partial views, for instance? What if you want to serialize a model to JSON for AJAX? Will things blow up if you forget to inherit from the base?) Instead, I recommend creating a separate view model for your menu which can be stored in the ViewData collection. Do this in your filter.

If you do end up using a base model, here is another answer that has a good example.


I think using two views vs. a single view with if/else logic comes down to code reuse. If the two menus are wildly different then I would suggest creating two views. If the menus are mostly the same except for for a few menu items then I would just use a single view with some if/else logic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜