ASP.NET MVC5中基于角色的菜单

时间:2016-11-15 01:14:11

标签: asp.net-mvc razor

我有一个遵循这种结构的菜单:

 <div id="sidebar-menu">
            <ul>
                <li class="active">
                    <a href="index.html" class="design active"><i class="icon-employee"></i><span> Employees </span></a>
                </li>

                <li>
                    <a href="Holiday.html" class="design"><i class="icon-holiday"></i><span> Holidays <span class="badge">6</span></span></a>
                </li>

                <li class="has_sub">
                    <a href="javascript:void(0);" class="design"><i class="icon-time"></i> <span> Time & Attendance </span> <span class="pull-right"><i class="mdi mdi-plus"></i></span></a>
                    <ul class="list-unstyled">
                        <li><a href="incident.html">Incidents</a></li>
                        <li><a href="hour.html">Hours</a></li>
                        <li><a href="pass.html">Passes</a></li>
                        <li class"active"><a class"active" href="disability.html">Disabilities</a></li>
                    </ul>
                </li>
    </ul>
    </div>

有一篇很好的文章关于如何创建它,但它只是一个级别的菜单,这是一个两级菜单。 http://techbrij.com/role-based-menu-asp-net-mvc

我想根据用户角色或验证动态显示它。

  

关于如何做的任何线索或示例?

1 个答案:

答案 0 :(得分:3)

根据用户角色在任何视图中动态显示内容。你可以这样做:

@if (User.IsInRole("roleName"))
{
    //Here you can write anything you want to show.
    <li><a href="incident.html">Incidents</a></li>
    <li><a href="hour.html">Hours</a></li>
    <li><a href="pass.html">Passes</a></li>
} else {
    <li><a href="signup.html">Sign Up</a></li>
    <li><a href="login.html">Login</a></li>
    <li><a href="aboutus.html">About Us</a></li>
}

如果您只想检查用户是否经过身份验证,您可以这样做:

@if (@User.Identity.IsAuthenticated)
{
    //Here you can write anything you want to show.
    <li><a href="incident.html">Incidents</a></li>
    <li><a href="hour.html">Hours</a></li>
    <li><a href="pass.html">Passes</a></li>
} else {
    <li><a href="signup.html">Sign Up</a></li>
    <li><a href="login.html">Login</a></li>
    <li><a href="aboutus.html">About Us</a></li>
}

如果菜单完全不同,最好做两个部分视图,并根据用户角色或用户进行身份验证从_Layout调用它们。这是一个例子:

@if (User.IsInRole("roleName"))
{
    //Here you can write anything you want to show.
    @Html.Partial("_RoleXXMenu")
} else {
    @Html.Partial("_RoleYYMenu")
}