Rendering HTML code that is created in the asp.nt mvc controller

I use a role-based menu. I have to generate the menu from the database dynamically. I have a role mapping table from which I can get the functions that appear in the role. Once I get this, I need to generate an HTML menu with <ul> and <li> . May I get a suggestion on how to do this. I mean creating an HTML script in the controller and mapping it to the appropriate view. Please help. Any suggestions are welcome.

 <ul id="menu"> <li> @Html.ActionLink("Home", "Dashboard", "User") </li> <li> <a href="#"><span>User</span></a> <ul> <li>@Html.ActionLink("Create User", "CreateUser", "User")</li> </ul> </li> <li> <a href="#"><span>Report</span></a> <ul> <li>@Html.ActionLink("ABC Report", "ABC", "Report")</li> <li>@Html.ActionLink("User Report", "UserReport", "Report")</li> </ul> </li> <li> <a href="#"><span>XYZ</span></a> <ul> <li>@Html.ActionLink("XYZ1", "XYZ1", "XYZ")</li> <li>@Html.ActionLink("XYZ2", "XYZ2", "XYZ")</li> <li>@Html.ActionLink("XYZ3", "XYZ3", "XYZ")</li> <li>@Html.ActionLink("XYZ4", "XYZ4", "XYZ")</li> </ul> </li> </ul> 

Over HTML, I have to build a controller and render the view.

0
source share
1 answer

I suggest creating a Menu class as shown below

 public class Menu { public string Text {get;set;} public string Controller {get;set;} public string Action {get;set;} } 

then in the viewModel add the viewModel property of type List<Menu> , then populate this collection in the controller dynamically from your database

then change your view below

 <a href="#"><span>XYZ</span></a> <ul> @for(var menu in Model.MenuList) { <li>@Html.ActionLink(menu.Text, menu.Action, menu.Controller)</li> } </ul> 
+1
source

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


All Articles