Place the user name anywhere

Everyone loves to see their name on a web page. It’s verification that the user is logged in properly, and perhaps validation of some sort? Well without getting into the psychology of it, I’d like to share a couple of approaches that I’ve taken to further personalize custom SharePoint pages.

The other day I was asked for a “quick script” to display the user’s login name elsewhere on the page. This assumes that you have not removed the login link located at the top right of the page. For this, you need to be using jquery. Thanks to Matt Huber’s blog for this idea, which I’ve taken a step further.

     var name = $(".s4-trc-container-menu span a span").text();

And place this html wherever you want the name to appear.

<span id="myname"></span>

Similarly, here’s a slightly more sophisticated way to create a custom login link, complete with user name. This is a c# based approach, so the following code can go in the code-behind or inline code – perhaps in the override of OnLoad.

if (HttpContext.Current.User.Identity.IsAuthenticated)
    litName.Visible = true;
    //a bit of calisthenics to remove the domain. 
    string[] displayNameComponents = SPContext.Current.Web.CurrentUser.Name.Split(new char[] { '\\' });
    litName.Text = displayNameComponents[displayNameComponents.Length - 1];
    lnkSignIn.Visible = true;

Here’s the placeholder for the asp page:

<asp:Literal Visible="false" ID="litName" runat="server"/>
<asp:Hyperlink Visible="false" NavigateUrl="/_layouts/Login.aspx" ID="lnkSignIn" runat="server">Sign In</asp:Hyperlink>

<asp:Hyperlink Visible="true" onclick="STSNavigate2(event,'/_layouts/SignOut.aspx')" ID="lnkSignOut" runat="server">Sign Out</asp:Hyperlink>

That’s all, folks!

Leave a Reply

Your email address will not be published. Required fields are marked *