Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Role Based Navigation

I've been trying to come up with a way to create a dynamic role based navigation solution for a project that I am working on.

The navigation should display only links that are relative to the users role, for example: an administrator will have links to view application statistics, manage customer accounts, ect... while a standard user would have links to manage their account, communicate with friends, ect..

I currently have a single partial view called Navigation with some basic conditional statements for role checking and a mix of markup for displaying the appropriate links. This works, but, I know it could quickly become unmanageable.

Navigation Partial View:

@if(User.IsInRole("Admin")) {
    <li><a href="#">Statistics</a></li>
    <li><a href="#">Accounts</a></li>
    <li><a href="#">Dashboard</a></li>
} 
@if(User.IsInRole("User")) {
    <li><a href="#">Account</a></li>
    <li><a href="#">Friends</a></li>
}
// code omitted

Is there a way to get this logic out of the view and let the Controller handle this?

like image 707
matt. Avatar asked Jun 09 '13 18:06

matt.


1 Answers

SOLUTION

As suggested, I created a ChildAction called Menu and partial views for each role. Inside the action I do some role checking using some conditional statements and render the appropriate view.

This keeps the conditional statements out of the views which makes it a lot cleaner solution.

I'm sure there are a few things that could be done to tidy it up and I will continue trying to improve it.

Here is the solution I used.

In the layout view where I wanted the menu to appear I used this.

@Html.Action("Menu", "Navigation")

Then I created a controller called Navigation and added a single Action called Menu.

public class NavigationController : Controller
{

    [ChildActionOnly]
    public ActionResult Menu()
    {
        if (Roles.IsUserInRole("Administrator"))
        {
            return PartialView("_NavigationAdmin");

        }

        return PartialView("_NavigationPublic");
    }

}
like image 191
matt. Avatar answered Sep 24 '22 14:09

matt.