Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Garret 69 posts 309 karma points
    Jun 03, 2020 @ 19:18
    Garret
    0

    How to get the MemberGroups for a Member?

    Hello,

    I succeeded in getting a list of Members of a specific MemberType. But now I would like to get the MemberGroups for each member

    IMemberService memberService = Services.MemberService;
    
    var students = memberService.GetMembersByMemberType(1044);
    
    @foreach(var student in students)
    {
    var groups = ""; /*get the membergroups for student*/
    
            <tr>
              <th scope="row">@student.Id</th>
              <td>@student.Name</td>
              <td></td>
              <td></td>
            </tr>
        }      
    

    I can't find a clue in the documentation.

    Any suggestions?

  • Anders Bjerner 487 posts 2990 karma points MVP 8x admin c-trib
    Jun 03, 2020 @ 20:11
    Anders Bjerner
    101

    Hi Garret,

    Umbraco relies on build-in logic in ASP.NET. While it still ought to be documented, that may be why it isn't as it's not directly a part of Umbraco.

    Anyways, you can use the Roles class. Given that your example is a Razor view, you don't have to import the class. Usage would be as shown below:

    string[] roles = Roles.GetRolesForUser(member.Username);
    

    The method will return a string array of the roles of the member. The method will hit the database, so it may be slow when looking up the roles for a lot of members.

    If you need a reference to the member group instead of just the name, you can use the member group service:

    IMemberGroup group = Services.MemberGroupService.GetByName(name);
    

    Or to avoid duplicate calls to the member group service, get all member groups, and then create a dictionary for faster lookups:

        Dictionary<string, IMemberGroup> memberGroups = Services.MemberGroupService
            .GetAll()
            .ToDictionary(x => x.Name);
    
  • Garret 69 posts 309 karma points
    Jun 04, 2020 @ 10:50
    Garret
    0

    Thanks Anders,

    Thanks finally got it working. I thought I already tried your suggestion..but I got the error that IMember didn't have a property Username. But copy/pasting your code worked perfectly.

    Maybe made a typo "UserName" instead of "Username".

    Thanks anyway, you really helped a struggling Umbracian out!

  • Jonathon Cove 9 posts 24 karma points
    Jan 23, 2024 @ 14:36
Please Sign in or register to post replies

Write your reply to:

Draft