I have an Angular project but this is not directly related to Angular and I just need the logic of create dynamic menu using tree that can also be similar as in ASP.NET MVC project. So, your suggestion for ASP.NET MVC, etc. will also be helpfu for me.
I use PrimeNG Tree and want to obtain menu from a table in MSSQL database:
Menu Table (the data was changed for example usage):
Id | Order | ParentId | Name |
1 1 0 Documents
2 1 1 Work
3 1 2 Expenses.doc
4 2 2 Resume.doc
5 2 1 Home
6 1 5 Invoices.txt
...
In order to populate the menu items, I need to generate a JSON string as shown below:
{
"data":
[
{
"label": "Documents",
"data": "Documents Folder",
"expandedIcon": "fa-folder-open",
"collapsedIcon": "fa-folder",
"children": [{
"label": "Work",
"data": "Work Folder",
"expandedIcon": "fa-folder-open",
"collapsedIcon": "fa-folder",
"children": [{"label": "Expenses.doc", "icon": "fa-file-word-o", "data": "Expenses Document"}, {"label": "Resume.doc", "icon": "fa-file-word-o", "data": "Resume Document"}]
},
{
"label": "Home",
"data": "Home Folder",
"expandedIcon": "fa-folder-open",
"collapsedIcon": "fa-folder",
"children": [{"label": "Invoices.txt", "icon": "fa-file-word-o", "data": "Invoices for this month"}]
}]
},
... //omitted for brevity
]
}
So, I have really no idea about the logic and database table design (menus). Should I generate the JSON above on the Controller or another place? Could you please post suggestions and sample approaches regarding to this issue?
Your database
Menu
table is fine to generate the treeview using the PrimeNG Tree plugin except that you may want to include an additional property for thedata
property if you want. I would however suggest you make theParentId
property nullable so that your top level item (Documents
) has anull
value rather that0
.In order to pass json in that format, your model need to be
You might also include other properties such as
to match the properties in the api
You also need a parent model for the
data
propertyTo generate the model, you controller code would be (note this is based on the
ParentId
field beingnull
for the top level item as noted above)For your icons, you should consider some
const
values or anenum
rather than hard-coding strings.