views:

235

answers:

1

Hi,

I wonder how can I populate the dropdown list with sites name within the site collection?

Thank you.

+3  A: 

Programmatically you mean?

SPSite.AllWebs

Use SPSite.AllWebs property that

Gets the collection of all Web sites that are contained within the site collection, including the top-level site and its subsites.

However, for your users, you will probably just get UnauthorizedAccessException (if you not to choose populate DropDownList with elevated privileges, but that depends on what do you wan't to do with that dropdown), because not everyone has permissions to enumerate all web's.

SPWeb.GetSubwebsForCurrentUser

In this case, you use SPWeb.GetSubwebsForCurrentUser Method that

Returns the collection of subsites beneath the current Web site of which the current user is a member.

However this method returns only subsites beneatath (1 level deep, that is) current web. You will need to recursively loop and call GetSubWebsForCurrentUser on each SPWeb you find.. err

I`d recommend...

You could use SPSecurity.RunWithElevatedPrivileges to call SPSite.AllWebs, then on each SPWeb you get, check if user has needed permissions, if so, add item to DropDownList.

In code, it looks something like this:

    DropDownList ddl = new DropDownList();
    SPUser currentUser = SPContext.Current.Web.CurrentUser;

    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        using (SPSite elevatedSite = new SPSite(SPContext.Current.Site.ID)) //you MUST create new SPSite instance
        {
            SPWebCollection elevatedWebs = elevatedSite.AllWebs;
            foreach (SPWeb elevatedWeb in elevatedWebs)
            {
                try
                {
                    if (elevatedWeb.DoesUserHavePermissions(currentUser.LoginName, SPBasePermissions.ViewPages))
                        ddl.Items.Add(new ListItem(elevatedWeb.Title, elevatedWeb.ID.ToString()));
                }
                finally
                {
                    if (elevatedWeb != null)
                        elevatedWeb.Dispose();
                }
            }
        }
    });
Janis Veinbergs