Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...