Create an interface ‘INavData’ which holds values for the menu and Create a class ‘NavData’ from the interface with all those properties.
- public interface INavData
- {
- string ImageFileNameWithNoExtn
- {
- get;
- set;
- }
- string AreaName
- {
- get;
- set;
- }
- bool IsActive
- {
- get;
- set;
- }
- bool IsDivider
- {
- get;
- set;
- }
- bool IsHeader
- {
- get;
- set;
- }
- string Text
- {
- get;
- set;
- }
- string ContorllerName
- {
- get;
- set;
- }
- string ActionName
- {
- get;
- set;
- }
- string AlternateUrl
- {
- get;
- set;
- }
- bool OpenNewWindow
- {
- get;
- set;
- }
-
- IEnumerable < INavData > Children
- {
- get;
- set;
- }
- }
Create a class ‘MenuBuild’ and a method ‘RenderMenu’ to hold the role based menu generation algorithm.
- public static class MenuBuild
- {
- public static IEnumerable < INavData > RenderMenu(IPrinciple User, Func < ActionResult, string > urlAction)
- {
- List < INavData > ComponentMenuList = new List < INavData > ();
-
- if (User.IsInRole("Authenticated_User"))
- {
- NavData Home = new NavData
- {
- IsActive = true,
- AlternateUrl = urlAction(MVC.Home.Actions.Index()),
- ActionName = MVC.Home.ActionNames.Index,
- ControllerName = MVC.Home.Name,
- Text = "Home"
- }
- ComponentMenuList.Add(Home);
- }
-
- List < INavData > subMenu1 = new List < INavData > ();
-
- if (IPrincipleExtensions.IsInAnyRole(User.IsInRole, ComponentViewer.ComponentViewerRoles))
- {
- NavData newCompMenu1 = new NavData
- {
- IsActive = true,
- AlternateUrl = urlAction(MVC.Comp.Actions.Index()),
- ActionName = MVC.Comp.ActionNames.Index,
- ControllerName = MVC.Comp.Name,
- Text = "Comp"
- }
- subMenu1.Add(newCompMenu1);
- }
-
- if (IPrincipalExtensions.IsInAnyRole(User.IsInRole, ComponentViewer.ComponentViewerRoles))
- {
- NavData newCompMenu2 = new NavData
- {
- IsActive = true,
- AlternateUrl = urlAction(MVC.Comp.Actions.Edit()),
- ActionName = MVC.Comp.ActionNames.Edit,
- ControllerName = MVC.Comp.Name,
- Text = "Comp Edit"
- }
- subMenu1.Add(newCompMenu2);
- }
-
- if (subMenu.Count > 0)
- {
- List < INavData > subMenu1Child = new List < INavData > ();
-
- NavData subMenu1Header = new NavData
- {
- Text = "New",
- Children = subMenu1Child
- }
- ComponentMenuList.Add(subMenu1Child);
- }
- }
- }
Write an extension class to the ‘IPrincipal’ with ‘IsInAnyRole’ method to loop the roles.
- public static class IPrincipalExtensions
- {
- public static bool IsInAnyRole(Func<string,bool> IsInRole, IEnumerable<string> roles)
- {
- foreach(string role in roles)
- if(IsInRole(role)) return true;
- return false;
- }
- }