我在一个ASP.Net MVC 3网站上工作. _Layout主视图包含一个菜单,我想根据您登录的内容以及您所处的角色隐藏菜单中的某些项目.
目前使用这样的代码
@if (HttpContext.Current.User.Identity.IsAuthenticated) { <li id="MyLearningTab">@Html.ActionLink("My Learning","MyLearning","Learning")</li> if (HttpContext.Current.User.IsInRole("Reporters")) { <li id="ReportTab">@Html.ActionLink("Reports","Index","Reports")</li> } if (HttpContext.Current.User.IsInRole("Administrators")) { <li id="DashboardTab">@Html.ActionLink("Dashboard","Dashboard","Admin")</li> <li id="AdminTab">@Html.ActionLink("Admin","Admin")</li> } }
我想重构这个更可读的东西,并提出了这样的东西
@if ((bool)ViewData["MenuMyLearning"]){<li id="MyLearningTab">@Html.ActionLink("My Learning","Learning")</li> } @if((bool)ViewData["MenuReports"]){<li id="ReportTab">@Html.ActionLink("Reports","Reports")</li>} @if ((bool)ViewData["MenuDashboard"]){<li id="DashboardTab">@Html.ActionLink("Dashboard","Admin")</li>} @if ((bool)ViewData["MenuAdmin"]){<li id="AdminTab">@Html.ActionLink("Admin","Admin")</li>}
我原来添加以下内容到我的基本控制器构造函数,以为我可以为这些属性设置ViewData
ViewData["MenuDashboard"] = User != null && User.Identity.IsAuthenticated && User.IsInRole("Administrators"); ViewData["MenuAdmin"] = User != null && User.Identity.IsAuthenticated && User.IsInRole("Administrators"); ViewData["MenuReports"] = User != null && User.Identity.IsAuthenticated && User.IsInRole("Reportors"); ViewData["MenuMyLearning"] = User != null && User.Identity.IsAuthenticated;
解决方法
这是我最后做的我为每个菜单项创建了一个名为MenuSecurity的辅助类,并显示哪些项目应该可见的静态布尔属性.每个房产都看起来像这样
public static bool DashboardVisible { get { return HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated; } }
然后我将菜单的部分视图整理为这样
@if (MenuSecurity.ReportsVisible){<li id="ReportTab">@Html.ActionLink("Reports","Reports")</li>} @if (MenuSecurity.DashboardVisible){<li id="DashboardTab">@Html.ActionLink("Dashboard","Admin")</li>} @if (MenuSecurity.AdminVisible){<li id="AdminTab">@Html.ActionLink("Admin","Admin")</li>}