1、思路:查找用户所有的组来匹配是否在特定的组(推荐)
不用担心组不存在而报错。
public static bool IsUserMemberOfGroup(SPUser user, string groupName) { bool result = false; if (!String.IsNullOrEmpty(groupName) && user != null) { foreach (SPGroup group in user.Groups) { if (group.Name == groupName) { // found it result = true; break; } } } return result; }
2、思路:查找特定组中是否有该用户
如果组不存在会报错
public bool IsExitUser(SPWeb web, string loginname, string groupname) { try { foreach (SPUser userlist in web.SiteGroups[groupname].Users) { if (userlist.LoginName.ToString().ToLower() == loginname.ToLower()) return true; } return false; } catch (Exception) { throw; } }
3、通过jquery判断,需要借助SPServices
function IsGroupMember(groupname) { //Checks user group membership to see if the current user is a member of "groupname" var booGroup = new Boolean(false); $().SPServices({ operation: "GetGroupCollectionFromUser", userLoginName: thisUserAccount, async: false, webURL: "weburl", completefunc: function(xData, Status) { if ($(xData.responseXML).find("Group[Name='" + groupname + "']").length == 1) { booGroup = true; } } }); return booGroup; } var thisUserAccount = $().SPServices.SPGetCurrentUser({ fieldName: "Name", debug: false });
调用的方式
if(IsGroupMember("用户组名称")==true) { //您的代码 }
如果直接,代码不起作用。
if(IsGroupMember("用户组名称")) { //您的代码 }