Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SharePoint get current user accountname?

Does SharePoint 2010 store the current user's accountname somewhere in a globally accessible JS object?

Every solution I can find involves some variation of an ajax web service call and this seems like an extremely heavy solution to access what should be a trivial piece of information.

Things I can access easily:

  • Get current user id from __spUserId
  • Get current user name by scraping the html of the ribbon (eg: $('#zz17_Menu').text())

But neither of these is the accountname.

Things I would rather not do:

  • Get current user info with a SOAP call to GetUserProfileByName
  • Get current user info by making an Ajax call for ../_layouts/userdisp.aspx
like image 360
Sinetheta Avatar asked Jun 20 '12 17:06

Sinetheta


2 Answers

For anyone else who stumbles across this, a year later I figured out how.

To your master page register SPSWC (if you're using Randy Drisgill's starter master it will already be there).

<%@ Register Tagprefix="SPSWC" Namespace="Microsoft.SharePoint.Portal.WebControls" Assembly="Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

Then, before you want to access a property (eg: UserName) pull in the data

<SPSWC:ProfilePropertyLoader runat="server"/>

Next, access one of the properties, I would recommend using TitleMode to embed it in a <script> element.

<script>
  var username = '<SPSWC:ProfilePropertyValue PropertyName="UserName" TitleMode="true" runat="server"/>';
</script>

We now use it as shown in this PasteBin demo to populate a global with a few properties like first name, last name, user name, profile picture, status.

like image 194
Sinetheta Avatar answered Oct 12 '22 13:10

Sinetheta


You really need to make a web service call to do it reliably. Thankfully, SPServices makes it quick and painless to do so.

http://spservices.codeplex.com/wikipage?title=$%28%29.SPServices.SPGetCurrentUser

$().SPServices.SPGetCurrentUser({
    fieldName: "Name",
    debug: false
});
like image 29
Rob Windsor Avatar answered Oct 12 '22 12:10

Rob Windsor