Client Object Model - Finding Sub Sites

Posted on 2/25/2011 @ 3:53 AM in #SharePoint by | Feedback | 1071 views

Here’s a code snippet that will give you sub-sites of a site -

  1: 	var context = SP.ClientContext.get_current();
  2: 	var webs = context.get_web().get_webs();	
  3: 	context.load(webs);
  4: 	context.executeQueryAsync(function(sender, args) {
  5: 		var webEnum = webs.getEnumerator();
  6: 		while(webEnum.moveNext()){
  7: 			var web = webEnum.get_current();
  8: 			alert(web.get_title());
  9: 		}
 10: 	}, function(){alert('err');});

Enjoy!

Sound off but keep it civil:

Older comments..


On 2/25/2011 10:06:55 AM @spjeff said ..
Does this retrieve all child webs recursively? Or just the first level down? Thanks for the post. It's good to see more Client OM examples in the blogosphere.


On 2/25/2011 1:11:12 PM Sahil Malik said ..
Only one level deep - though you can easily make it recursive.


On 3/23/2011 2:18:23 AM Raj said ..
Hi...

Thank u for the article.

Could you please help me in code that finds logged-in user belongs to specific sharepoint group or not?

actually i have to hide a controle using CSS based on logged in user permission with


minimal effort. where i thought client object model can fulfil my req.

regards

raj


On 11/1/2011 10:36:53 AM Siva Subramanian said ..
public static Web getSubWebs(Web orootweb ,string path)


{


Web orWebsite = null;


try


{


ClientContext clientContext = new ClientContext( path+orootweb.ServerRelativeUrl );


Web oWebsite = clientContext.Web;


clientContext.Load(oWebsite, website => website.Webs, website => website.Title);


clientContext.ExecuteQuery();


Console.WriteLine("Available sites Count: " + oWebsite.Webs.Count);


for (int i = 0; i < oWebsite.Webs.Count; i++)


{


Console.WriteLine("Site Title: " + oWebsite.Webs[i].Title);


orWebsite = oWebsite.Webs[i];


getSubWebs(orWebsite,path);


}


}


catch (Exception ex)


{

}


return orWebsite;

}

static void Main(string[] args)


{


Sub obj = new Sub();


ClientContext clientContext = new ClientContext("http://triad102:5000");


Web oWebsite = clientContext.Web;


clientContext.Load(oWebsite);


clientContext.ExecuteQuery();


Web oweb= getSubWebs(oWebsite, "http://triad102:5000");


}