8

I am writing my first MVC 3 aplication (in ASP.NET) and I don't know how I can(should) display the menu for different users.

My app is created as MVC3 Web Application and the menu look like this:

<div id="menucontainer">
            <ul id="menu">
                <li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("Info", "Info", "Home")</li>
            </ul>
</div>

I created two types of roles: user and admin. Now, I want to show another links for user(Projects, Profile) and for admin(Manage Projects, Manage Accounts, Manage news).

How I should do that?

Jacob Jedryszek
  • 6,365
  • 10
  • 34
  • 39
  • 2
    Have you looked at this question: [Building an ASP.NET MVC Master Page Menu Dynamically, Based on the current User's “Role”](http://stackoverflow.com/questions/2203320/building-an-asp-net-mvc-master-page-menu-dynamically-based-on-the-current-users), seems to address nearly the same question you have AND people have answered it. – Roman Feb 07 '11 at 01:54

1 Answers1

7

I found solution:

<div id="menucontainer">
            <ul id="menu">
                <li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("Info", "Info", "Home")</li>
                @if ( Request.IsAuthenticated && HttpContext.Current.User.IsInRole
( "user" ) ) {
                     <li>Projects link</li>
                     <li>Profile link</li>
                }
                @if ( Request.IsAuthenticated && HttpContext.Current.User.IsInRole
( "admin" ) ) {
                     <li>Manage Projects link</li>
                     <li>Manage Accounts link</li>
                }
            </ul>
</div>
Jacob Jedryszek
  • 6,365
  • 10
  • 34
  • 39
  • 9
    You shouldn't put that much conditional logic into your view. If you insist on doing it this way, you should really put both of those checks into your action and add simple boolean properties to your ViewModel. – Roman Feb 08 '11 at 16:03
  • [link](http://forums.asp.net/t/1903464.aspx?having+5+roles+and+one+layout+for+all+of+them+with+custom+menu+per+roles+in+mvc) @ehoog this logic should not be applied in the view, as it makes the view code very messy and it violates the principles of MVC. This logic should be in the controller. I suggest you: Create a Model class In the Controller action, fill the model with the data for the menu items (depending on role). In the view, generate the menu using the menu data from the model. – sosha Nov 04 '15 at 09:12