Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 have 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 ?

like image 412
Mathieu Avatar asked Jan 20 '23 04:01

Mathieu


1 Answers

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.

like image 99
Tejs Avatar answered Feb 12 '23 07:02

Tejs