Role Based Navigation

感情迁移 提交于 2019-11-27 14:08:19

问题


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?


回答1:


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

}


来源:https://stackoverflow.com/questions/17012643/role-based-navigation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!