Best practices for viewing and dynamic menus - ASP.NET MVC

I am launching a new website in asp.net MVC with a dynamic menu that varies depending on the user. But that's not all. I use 2 different layouts (Razor layouts) depending on the user, and 2 different layouts have a different menu. So, I have 2 different layouts with two different speaker menus.

I would like to use the same view for two layouts with one view model for each view. I use an action filter to define the layout. It’s a good idea to create a base class β€œViewModel” that contains data for displaying both menus (even if only one menu is created each time) and create a child of this base class for my entire view model (one view model for each view).

I want to know if this is a good practice. Is this the case when I have to use 2 views (one per layout) and use partial views for the common part?

And if there are any differences from what I want to display in the view depending on the layout, should I use 2 views instead of one?

Any recommendations?

+4
source share
3 answers

In my opinion, it would be best practice to have one presentation model for your presentation, and the property on it contains 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 the implementation of the dynamic menu data to your view model based on which menu you want to display for this user. Then, in your opinion, you can call:

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

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

+7
source

I would highly recommend using a base view model that has menu properties because it is very tough. (What happens if you use partial views, for example? What if you want to serialize the JSON model for AJAX? Will things explode if you forget to inherit from the base?) Instead, I recommend creating a separate view model for yours that you can save to collection ViewData. Do this in your filter.

If you are using a basic model, here is another answer that has a good example.

+2
source

I think that using two views against one view with if / else logic comes down to reusing code. If the two menus are very different from each other, I would suggest creating two views. If the menu is basically the same, with the exception of a few menu items, I would just use the same view with some if / else logic.

0
source

Source: https://habr.com/ru/post/1344976/


All Articles