Question

We are using MVC 3 to build a Web site with dynamic menu options so that users only see menu options (action Links) that they are allowed to see based on group and individual privileges.

How can we add dynamic menu options (links to partial views) at run time? Do we hard code all the links of all the partial views and turn of the ones that are not required using a visibility option? Can we add the links dynamically from a database?

Let me clarify. WE have admins that have access to all menu options like Manage Users, Manage Groups, Manage Suppliers, Manage products and Manage Orders. We have regular sales staff who only need Manage Supliers and Manage Orders. So based on this we only need to show the links that say Manage Orders and Manage Supplier. Hence they dynamic nature of the links I am trying to set up. We have the permissions set up in the DB.

Jawahar

Was it helpful?

Solution 2

I found a way of doing this using Method extension with IPrincipal

public static bool IsAllowed(this IPrincipal p, string menuid) { 
if (p.Identity.IsAuthenticated) { 
         //Code here to verify privillegs against Database
     } 
     return false; 
} 

This would keep it fairly neat in you Layout.cshtml. 

@if (User.IsAllowed("menuchoice1")) { 
        <a href="@Url.Action(...)">...</a> 
} 
@if (User.IsAllowed("menuchoice2")) { 
      <a href="@Url.Action(...)>...</a> 
} 

Hope this help others looking for similar options

OTHER TIPS

I am not sure I entirely understand what you mean when you say "links to partial views". You never really have a hyperlink to a partial view. The two possibilities I can think of are either you want to know how to embed the partial view conditionally, or you want to have hyperlinks to a controller action which returns the partial views.

In the first case, you can just put the @Html.RenderPartial call inside of an @if (myCondition == true) block. With that, the partial view will only be displayed if the condition passes.

In the second case, you can just always call the controller action. In your controller, only return the PartialView if your condition matches. Otherwise, return null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top