Udostępnij za pośrednictwem


Getting the Current User Name or ID in SharePoint using SharePoint Designer (no code)

A colleague sparked my interest in this today by asking me if getting the current user ID was possible without writing code.  This would be a very trivial task by creating a custom web part but with that comes deployment, maintenance, support, etc.  He had a simple requirement to pass the UserID in the query string and thought it would be overkill to do this using code, and I agreed.  This put me on a mission to find out if this was possible using SharePoint designer.  The usual Internet searches didn't return anything useful so once I figured it out I decided that this needed to be posted somewhere.  So here is how you do it:

 

Using SharePoint designer open up the Data Source Library Pane

Hover over any library or list, using the drop down select "Show Data"

image

Next you will want to have SharePoint Designer insert a DataFormWebPart for you.  These last two steps aren't really necessary, you could write all the markup by hand, but I find it is usually easier to have SPD do this for you, and then go back and clean it up, than it is to remember everything that you need and start from scratch.  For this part I selected the Title field and used a Multiple Item View Form, you can select different fields/views as your situation calls for.

image

Now we can get to what this post was really about, getting the UserName and/or the User ID.  To get the UserName all you need to do is add an XSL parameter.  A little known fact here is that any parameter that is found in the parameter bindings section of the data source element can also be passed to the XSL using an XSL parameter.  To be clear about what I added refer to the screen shot below, I have removed all the irrelevant XSL to make this easier to understand.

image 

The above will show you the what SharePoint display's the user name as.  This was a step in the right direction, but I still needed to actual user ID.  To get this I decided to go the server variable route.  Here is the documentation straight from MSDN on the three variables that are probably of interested for this situation.

AUTH_USER

The name of the user as it is derived from the authorization header sent by the client, before the user name is mapped to a Windows account. This variable is no different from REMOTE_USER. If you have an authentication filter installed on your Web server that maps incoming users to accounts, use LOGON_USER to view the mapped user name.

LOGON_USER

The Windows account that the user is impersonating while connected to your Web server. Use REMOTE_USER, UNMAPPED_REMOTE_USER, or AUTH_USER to view the raw user name that is contained in the request header. The only time LOGON_USER holds a different value than these other variables is if you have an authentication filter installed.

REMOTE_USER

The name of the user as it is derived from the authorization header sent by the client, before the user name is mapped to a Windows account. If you have an authentication filter installed on your Web server that maps incoming users to accounts, use LOGON_USER to view the mapped user name.

I decided to use the LOGON_USER variable, but note that you can use any server variable here, your not limited by SPD in any way.  To do this I had to add the server variable to the ParameterBindings as well as the XSL.  The end result of my DataFormWebPart is below.

 <WebPartPages:DataFormWebPart runat="server" 
        IsIncluded="True" 
        FrameType="None" 
        NoDefaultStyle="TRUE" 
        ViewFlag="0" 
        Title="Shared Documents" 
        ListName="{EF49CFE7-C6C4-42D6-8FCB-B10D6CDC0A35}" 
        Default="FALSE" 
        DisplayName="Shared Documents" 
        __markuptype="vsattributemarkup" _
        _WebPartId="{E39B973F-F567-4AE6-9913-36710D1ADA1A}" 
        id="g_e39b973f_f567_4ae6_9913_36710d1ada1a" 
        __AllowXSLTEditing="true" 
        WebPart="true" 
        Height="" 
        Width="" __WebPartId="{633D5B43-5675-4363-8F69-9BA87A3776ED}">
    <DataSources>
        <SharePoint:SPDataSource runat="server" 
            DataSourceMode="List" 
            UseInternalName="true" 
            selectcommand="&lt;View&gt;&lt;/View&gt;" 
            id="Shared_x0020_Documents1"><SelectParameters><WebPartPages:DataFormParameter 
            Name="ListID" 
            ParameterKey="ListID" 
            PropertyName="ParameterValues" 
            DefaultValue="EF49CFE7-C6C4-42D6-8FCB-B10D6CDC0A35"/>
        </SelectParameters></SharePoint:SPDataSource>
    </DataSources>
    <ParameterBindings>
    <ParameterBinding Name="ListID" Location="None" DefaultValue="EF49CFE7-C6C4-42D6-8FCB-B10D6CDC0A35"/>
    <ParameterBinding Name="dvt_apos" Location="Postback;Connection"/>
    <ParameterBinding Name="UserID" Location="CAMLVariable" DefaultValue="CurrentUserName"/>
    <ParameterBinding Name="Today" Location="CAMLVariable" DefaultValue="CurrentDate"/>
    <ParameterBinding Name="LogonUser" Location="ServerVariable(LOGON_USER)"/>
</ParameterBindings>
    <datafields>@FileLeafRef,Name (for use in forms);@Title,Title;@Approval,Approval;
    @CollectS,Collect Signatures;@CollectF,Collect Feedback;@ID,ID;@ContentType,Content Type;
    @Created,Created;@Author,Created By;@Modified,Modified;@Editor,Modified By;
    @_CopySource,Copy Source;@CheckoutUser,Checked Out To;@_CheckinComment,Check In Comment;
    @CheckedOutTitle,Checked Out To;@CheckedOutUserId,ID of the User who has the item Checked Out;
    @FileDirRef,Path;@FSObjType,Item Type;@HTML_x0020_File_x0020_Type,HTML File Type;
    @File_x0020_Type,File Type;@IsCheckedoutToLocal,Is Checked out to local;@_SourceUrl,Source Url;
    @_HasCopyDestinations,Has Copy Destinations;@ContentTypeId,Content Type ID;@_ModerationStatus,Approval Status;
    @_UIVersion,UI Version;@Created_x0020_Date,Created;@FileRef,URL Path;@File_x0020_Size,File Size;
    @_UIVersionString,Version;@ParentVersionString,Source Version (Converted Document);
    @ParentLeafName,Source Name (Converted Document);@TemplateUrl,Template Link;</datafields>
    <XSL>
<xsl:stylesheet xmlns:x="https://www.w3.org/2001/XMLSchema" 
                xmlns:d="https://schemas.microsoft.com/sharepoint/dsp" 
                version="1.0" 
                exclude-result-prefixes="xsl msxsl ddwrt" 
                xmlns:ddwrt="https://schemas.microsoft.com/WebParts/v2/DataView/runtime" 
                xmlns:asp="https://schemas.microsoft.com/ASPNET/20" 
                xmlns:__designer="https://schemas.microsoft.com/WebParts/v2/DataView/designer" 
                xmlns:xsl="https://www.w3.org/1999/XSL/Transform" 
                xmlns:msxsl="urn:schemas-microsoft-com:xslt" 
                xmlns:SharePoint="Microsoft.SharePoint.WebControls" 
                xmlns:ddwrt2="urn:frontpage:internal">
    <xsl:output method="html" indent="no"/>
    <xsl:decimal-format NaN=""/>
    <xsl:param name="dvt_apos">'</xsl:param>
    <xsl:param name="UserID"/>
    <xsl:param name="LogonUser"/>
    <xsl:variable name="dvt_1_automode">0</xsl:variable>
    <xsl:template match="/">
    
    <xsl:value-of select="$UserID"/><br/>
    <xsl:value-of select="$LogonUser"/>
    
    </xsl:template>
    </xsl:stylesheet>    </XSL>
</WebPartPages:DataFormWebPart>
 And the screen shot...

image

 

And that does it, you can now show user name or user ID without using any code.  An important side lesson of this is the fact that you can use anything in the parameter binding session in your XSL as well. 

 

Hope this helps.

Comments

  • Anonymous
    July 03, 2008
    Thanks a lot! Great job! but I want to get all group permission of current user, Can use xslt do that?

  • Anonymous
    August 09, 2008
    Thank you so much!  I've been racking my brain on this problem for a while.  Trying to do sharepoint development with the restriction of "No server-side code" allowed is tricky, and this technique is very valuable.

  • Anonymous
    October 15, 2008
    Well - but you only solved part of  your colleagues problem which also included "...to pass the UserID in the query string ..." !  

  • Anonymous
    November 20, 2008
    Is there a way to pull a list of the current user's site group memberships? I want to show or hide a specific column based on whether or not the current user is a member of a custom Approvers group I set up. The only way I know to do it now is by User ID, which means anytime I have to change the list, I have to also alter the code that "hides" the column for non-approvers. Any ideas on how to do this without writing C#? Thanks, Tuesday

  • Anonymous
    December 18, 2008
    if you enter [Me] as the default value for a text field and set it to calculated, it returns the userID

  • Anonymous
    April 21, 2009
    Thanks, works great!!  Anyone know how to pass this info on to an Oracle form or another app?

  • Anonymous
    May 10, 2009
    Brilliant. Just brilliant. Thanks a bunch. Chill...

  • Anonymous
    June 09, 2009
    Can i do this with out using sharepoint designer? My case is like this i have a custom list which consist of a coulmn called NAME.When i click New i want to get the current users name on that Name field.

  • Anonymous
    June 11, 2009
    Is there a way to store the current user name in a list?

  • Anonymous
    June 24, 2009
    Hi, I would like to get the current user name in a variable that I can use in the XSL of my search result webpart. I would like to format my result list depending on a comparison between the current user and the "exracted to" field. Is there a way to do this ? Many thanks !

  • Anonymous
    June 24, 2009
    You are amazing ! Nice Approach

  • Anonymous
    July 08, 2009
    Can you have it show the logged in user in a specific field in a sharepoint form?

  • Anonymous
    July 22, 2009
    I got the value of UserId returned using Javascript below. var abc = document.getElementById("WebPartg_641f8149_8c06_46c4_b2e6_91b55fd14776"); alert("Hello " + abc.innerText ); The value comes back inside a div tag. So need the id. Is there a better way?

  • Anonymous
    September 09, 2009
    Nice method, allowed me to expose the UserID to javascript in order to prepopulate a people picker on a custom list form.   Used Andy Bonner's method (http://cs.vbcity.com/blogs/skullcrusher/archive/2008/11/03/set-sharepoint-peoplepicker-field-mark-2.aspx) to populate the field, but needed an easy way to expose the UserID for Andy's javascript to grab it.  This did the trick. Thanks again.

  • Anonymous
    September 21, 2009
    This is really great. I would also want to know if there a CAMLVariable to retrieve an user's email ID?

  • Anonymous
    October 01, 2009
    Nice !!!!!!!! get sharepoint user and group, it is simple. Try this too, <a href ="http://sarangasl.blogspot.com/2009/10/sharepoint-user-groups.html"><b>Get Current SharePoint user</b></a>

  • Anonymous
    October 01, 2009
    Nice !!!!!!!! get sharepoint user and group, it is simple. Try this too, http://sarangasl.blogspot.com/2009/10/sharepoint-user-groups.html

  • Anonymous
    October 17, 2009
    Hi, Thank you for this. I used your code and it works great. I had an additional need.  I needed to filter my dataview based on a substring of LogonUser. In my case my LogonUser code are initials and numbers such as  P16012.  I had to filter based on just the numbers 6012. My  LogonUser presents  as COMSERVEP16012. So I added the following code to isolate just the numbers I need as a parameter <xsl:param name="LogonUser"/><xsl:param name="LoginNumbers"><xsl:value-of select="substring($LogonUser,12)"/></xsl:param> In the dataview I just filtered on the parameter added above [$LoginNumbers=@COM_x0020_ID] I hope others find this useful

  • Anonymous
    October 22, 2009
    So close.  I am trying to take the a parameter like LoginNumbers above and set it as a parameter in a SqlDataSource UpdateQuery to update an operator field.  How to I reference back to that? Thank you.

  • Anonymous
    November 04, 2009
    The comment has been removed

  • Anonymous
    November 10, 2009
    You can also do this for a SqlDataSource using a ControlParameter.  This lets you pass the user's ID into a query before databinding.  I haven't found a way to get the user's name from this, though. <asp:SqlDataSource ID="Data" runat="server" ConnectionString="..." SelectCommand="SELECT @user UserID"> <SelectParameters> <asp:ControlParameter Name="user" ControlID="Data" PropertyName="Page.Request.ServerVariables['AUTH_USER']" /> </SelectParameters> </asp:SqlDataSource> <asp:DetailsView runat="server" DataSourceID="Data" />

  • Anonymous
    February 03, 2010
    Hi Tenorman, How did you get the domainuserID(P16012)? my LOGON_USER parameter gives me empty string.

  • Anonymous
    February 18, 2010
    Thanks so much for this post.  I wanted to display the current user name in a custom list form and was able to simply include the following portion in the cell where I wanted it to show: <xsl:value-of select="$UserID"/> The only other task was to pass the parameter to the stylesheet (it was referenced in the parameter bindings section for the custom list form, just hadn't been passed to be able to call from the xsl template): <xsl:param name="UserID"/> Thanks for the post! Chanda

  • Anonymous
    March 01, 2010
    Excellent Thank you so much...

  • Anonymous
    August 01, 2010
    thank you for the article and special thank you to Jeremy Green for the sql connection details, I have been trying to do this for a while now and the sql connection thing is so simple and completely solves my problem! it's made it a great monday for me! :-)

  • Anonymous
    November 08, 2010
    Thanks a lot... It really helped me alot. I was looking for the same kind of solution.

  • Anonymous
    January 05, 2011
    Good job. Another way to get the user id would be to simply hoover over the username and find the ID in the bottom left corner :)

  • Anonymous
    May 15, 2011
    It's working like a charm...! Thanks you

  • Anonymous
    September 18, 2011
    This works great, I just wanna ask, how will I pass the value to a textbox?

  • Anonymous
    January 09, 2013
    Hi, I can't make it work. We need to show the current username in a page of the sharepoint intranet, and have a link that's sends the username embed, like this: </a href='test.php?id=username'/>click here</a> Or any why that sends the username to an external site. Please help me, thanks

  • Anonymous
    May 16, 2013
    This helped me immensely, thank you!  I used it to filter a list of messages by the name...  been looking for this for a while. thanks again!

  • Anonymous
    November 26, 2013
    Your post has helped me a lot. However just for information, when we upgraded to SP2013, i finally realised that the username is prefixed with i:0#.w| because of som changes in the claims authorization mechanism. Take care in the SQL query.

  • Anonymous
    February 17, 2014
    thanks for sharing this..

  • Anonymous
    April 14, 2014
    I am trying filter a external list by username. Unfortunately the list has loginname minus the 'domain ' .   Ideally I would like to perform   <ParameterBinding Name="LogonUser" Location="substring-after(ServerVariable(LOGON_USER),'')"/> to get the correct value to query. I am not sure how to achieve this. Please suggest a solution.

  • Anonymous
    September 22, 2015
    I just found this as well: <asp:LoginName runat="server" id="loginName" FormatString="<script>var _user = {0}</script>"></asp:LoginName>