May 2, 2007

MOSS: How to hide UI elements according to user's Audience

Problem:I need to hide different UI elements from the master page depending on the current user's audience. SPSecurityTrimmedControl apparently knows nothing about audiences so it cannot be used.

Solution:Changing master pages on the fly is possible, as described here, but if you'd just want to hide some specific things without making whole lotta master pages this custom control might come handy.

The custom control inherits from SPSecurityTrimmedControl so you could possibly (haven't tested) use some functionality of that control too. It's not necessary to inherit it from SPSecurityTrimmedControl, of course, you could just inherit from WebControl if you're only interested in the Audience functionality.

3 comments:

If you want to target specific web parts, you can just use the Audience functionality of a web part. Otherwise you can use SPWeb.IsCurrentUserMemberOfGroup(int groupId), or SPGroup.ContainsCurrentUser. Current SPWeb's associated groups (Member, Visitor, Owner) you can get using SPWeb.AssociatedGroups, or SPWeb.AssociatedMember/Owner/VisitorGroup.

Thanks for this solution! It is a great addition to use with custom UI Elements. To answer the use with multiple SharePoint Groups instead of Audiences question, you can use this solution with some modifications to how you add it on a page to achieve this. SharePoint Groups can be used as an Audience without compiling an actual Audience in Central Admin. So with this solution all you have to do is set a Register Tagprefix for the solution on the page or MasterPage you need to use it on. Then for the Tag around your object, set it with your Tagprefix and a unique ID (unique ID if you want to use this feature more than once on a page). You can then set an AudienceString with multiple SharePoint Groups separated with a comma....like..... Group1,Group2,Group3,Group4. Works like a charm. I would actually post the code so it’s more obvious, but your blog won't allow code postings. I could try to post on my own blog with a reference to this post so it’s clearer, if you would like see what I mean. Just let me know.