views:

202

answers:

2

In ASP.NET what's the best way to do the following:

  1. Show certain controls based on your rights?
  2. For a gridview control, how do you show certain columns based on your role?

I'm thinking for number 2, have the data come from a role specific view on the database.

+4  A: 

Instead of actually using roles to hide/show certain controls, I would suggest having another layer of permissions for each role and show/hide based on those instead.

That way you can redefine what permissions a role has and won't have to change your code.

Also, this allows you to make new roles in the future and just assign a set of permissions to the role.

As for controls, yes... I would just set the Visible property on the control based on the user.IsInRole("permissionname") value.

For grids I would do the same... set the Visibility of the columns to the IsInRole boolean value.

//Delete Icon Column
gridViewContacts.Columns[0].Visible = user.IsInRole("DeleteAnyContact");

I would make create your permissions in a very granular nature.. such as

  • ViewAnyContact
  • ViewOwnContact
  • EditOwnContact
  • EditAnyContact
  • AddAnyContact
  • DeleteOwnContact
  • DeleteAnyContact
  • Etc...
Elijah Manor
+1  A: 

If you're going the role-based route, ASP.NET (since version 2.0) has had a variety of membership controls available which might help in this scenario. Assuming (and this could well be a faulty assumption) that you're using the in-box membership provider, you can actually use the LoginView control to get #1 handled.

The way it works is that the LoginView can use RoleGroups and their associated ContentTemplates to customize the view for the user based on role. This works seamlessly with the in-box membership provider; I believe if you build your own membership provider based on Microsoft's technology it will also work. (I haven't done this latter step.)

Conceivably, you could use it for #2, but it'd wind up with duplicated code and effort, which isn't my personal preference. I think your choice of using role-specific SQL views to drive that table may be better than this option. (There are other options as well, of course, which may be better.)

I will second Elijah Manor's recommendation of using permissions instead of roles. Generally, that's my preference as well. (And I was surprised to discover that the membership provider technology didn't go to that level.) In any permission-centric scenario, though, you will essentially have to roll everything yourself. (I've done this, and while it's very flexible, the code to secure any given page can get hairy.)

EDIT: I apologize; I meant to include a link for the LoginView control. DotNetJunkies has a tutorial on it.

John Rudy