Monday, August 29, 2016

LoginView Control in SharePoint Web Part

When developing on a SharePoint site, if you have the need to show your logged in users content that you don't necessarily want to show your anonymous users, the LoginView control is for you.

Keeping it simple, we pass a string to the LoggedInTemplate class constructor that inherits from the iTemplate interface.

// we'll show the label only when a user is logged in. Intended for employees only.
LoginView lv = new LoginView();
Label usernameLabel = new Label();
usernameLabel.Text = "Hello There";
lv.LoggedInTemplate = new LoginViewTemplate(usernameLabel);
Controls.Add(lv);

// Logged in user and anonymous templates inherited from iTemplate interface.
    class LoginViewTemplate : ITemplate
    {
        private Label _label;
        public LoginViewTemplate(Label label)
        {
            _label = label;
        }
        public void InstantiateIn(Control container)
        {
            container.Controls.Add(_label);
        }
    }

// not used in this example
    class AnonymousTemplate : ITemplate
    {
        private Label _label;
        public AnonymousTemplate(Label label)
        {
            _label = label;
        }
        public void InstantiateIn(Control container)
        {
            container.Controls.Add(_label);
        }
    }

For further filtering out your logged in users to see specific content, use RoleGroups instead.

No comments:

Post a Comment