简体   繁体   中英

Get first and lastname from current user in Sharepoint

How do I get the first and last name of the current user in sharepoint? My guess is to use the UserProfile property but i cant get it to work. Do i need a nugetpackage for that? But i dont have internet connection from my virutal machine so i cant do that.

You can create a UserCollection or User variable. Then you can split the Title text by " ". This will help you get the First Name, LastName as well as MiddleName.

   UserCollection managerGroupUsers = _managerGroupName.Users;                         
                        clientContext.Load(managerGroupUsers);
                        clientContext.ExecuteQuery();
                        string[] Username=null;
                        foreach (User u in managerGroupUsers)
                        {
                             Username= u.Title.Split(' ');
                            string firstName = Username[0];
                            string LastName = Username[1];

                        }

Create the clientcontext for your site and add the following code `

Group _managerGroupName=null; 
    if (clientContext != null)
                        {
                            var siteColl = clientContext.Site;
                            var web = siteColl.RootWeb;
                            GroupCollection groupColl = web.SiteGroups;`

                            clientContext.Load(siteColl);
                            clientContext.Load(web);




                            clientContext.ExecuteQuery(); 


    _managerGroupName = web.AssociatedOwnerGroup;
                                clientContext.Load(_managerGroupName);
                                clientContext.ExecuteQuery();                  
    UserCollection managerGroupUsers = _managerGroupName.Users;
            clientContext.Load(managerGroupUsers);
            clientContext.ExecuteQuery();
            string[] Username = null;
            foreach (User u in managerGroupUsers)
            {
                Username = u.Title.Split(' ');
                string firstName = Username[0];
                string LastName = Username[1];

            }     

It looks like from your pastebin you're making a new server side web part. So you don't need Microsoft.SharePoint.Client. The previous examples are done with client object model, but you're using server object model. Replace the contents ot your onStart() function with this:

SPUser currentUser = SPContext.Current.Web.CurrentUser;
string[] nameSegments = currentUser.Name.Split(' ');
this.Controls.Add(new LiteralControl("<div>First Name: " + nameSegments[0]));
this.Controls.Add(new LiteralControl("<div>Last Name: " + nameSegments[1]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM