问题
I am implementing a role based menu. I have to generate the menu from the database dynamically. I have a role-feature mapping table from where I can get the features that are mapped to the role. Once I get that I have to generate the HTML menus with <ul> and <li>
. Can I get suggestion as to how that be done. I mean generating the HTML script in controller and rendering it on to the respective view. Please help. Any suggestion is welcomed.
<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>
Above HTML I have to build in controller and render to the view.
回答1:
I suggest to create a Menu
class as below
public class Menu
{
public string Text {get;set;}
public string Controller {get;set;}
public string Action {get;set;}
}
then in your viewModel
add a property MenuList
of type List<Menu>
then fill that collection in your controller dynamically from your database
then change your view as 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>
来源:https://stackoverflow.com/questions/28186208/rendering-html-code-in-view-which-is-generated-in-controller-of-asp-nt-mvc