ASP.NET MVC - show hide user controls depending on role

In an MVC2 (c#) app I checking for role in master page and displaying menu items like this

<% if (Model.IsUserAdmin)
                       { %>
                    <li><a id="lnk" runat="server" href="/Admin/">Admin Area</a></li>

and so on.

There are 3 roles in the app  SuperUser, Admin, User

Dependant who is logged into the app I want to show a logged in user's section (user control) that shows
different data for each role.

I am thinking of maybe 3 user controls one for each role and show/hide depending on role?

Or just one user control and show/hide dependant on role.

The scenario is

User    -  display logged in name
Admin - display logged in name AND  dropdown list of things
SuperUser  - display logged in name AND  dropdown list of things AND another dropdown list of things

Who is Participating?
Carl TawnSystems and Integration DeveloperCommented:
Very simply you would do something like the following, which uses a hard-coded list of drop down options:
<% if (Model.IsAdmin) { %>

    <%: Html.DropDownList("ADropDown", new List<SelectListItem> { new SelectListItem { Text = "One" }, new SelectListItem { Text = "Two" }, new SelectListItem { Text = "Three" } }) %>

<% } %>

Open in new window

Carl TawnSystems and Integration DeveloperCommented:
Well for starters it's MVC so there is no such thing as a user control :)

I think your best option would be to render a PartialView and let it decide what to show based on your model. That way the logic is encapsulated in your PartialView rather than the main View, and then you only have to worry about telling it where to draw.
ToString1Author Commented:

Could you give a quick  example please
Carl TawnSystems and Integration DeveloperCommented:
Well, i'm going to make a bit of a sweeping assumption that you know how to add a PartialView to your project, and that you know (as you would appear to based on your original sample) that you know how to define the logic to control wat the PartialView displays.

To actually display the partial view and pass it your Model, you would use something like the following in your main view:
<%: Html.RenderPartial("UserAdmin", Model);

Open in new window

Which assumes your partial view is named "UserAdmin" and that it is strongly typed to the same Model as your main view.
ToString1Author Commented:
OK thanks

So inside the partial view I would show/hide divs based on role?   Or would these be panels?

Just a quick example of showing hiding dropdowns would be good

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.