Share via


Add subsites and provide navigation functionality in MOSS 2007 - a code approach!

Creating sub sites through MOSS 2007 interface, creates a top navigation automatically. You’ll be able to reach the sub site and back to the root page with on click (actually 2 J - to and fro you see). However, this seems to be missing when we create a sub site using object model code.

Usually to create a sub site, the following code snippet is used:

ParentSite = new SPSite(strUrl);

ParentWeb = ParentSite.OpenWeb();

ChildWeb = ParentWeb.Webs.Add(strChildName, strChildName, strChildName, (uint)1033, "SridharReflector.stp", false, false);

It’s in the shortest possible form though. But a sharp intellect should be able to understand it J. There is couple of manifestations of the above code snippet, but I am using a STP file as my template here. However, the problem is: after this code runs, it creates a sub site no doubt – but the navigation to the sub site and back to the root site wouldn’t be created. Well, this was exactly what one of my customer wanted L. My *searching* skills might be bad, but believe me, I tried, tried n’ tried – end result couldn’t find an easy way to accomplish this.

However, I came up with a dirty (I mean very dirty) way to accomplish this. Code snippet is given below:

ParentSite = new SPSite(strUrl);

ParentWeb = ParentSite.OpenWeb();

ChildWeb = ParentWeb.Webs.Add(strChildName, strChildName, strChildName, (uint)1033, "SridharReflector.stp", false, false);

ChildWeb.Update();

ChildSite = new SPSite(ChildWeb.Url);

DChildWeb = ChildSite.OpenWeb();

SPNavigationNode ParentNode = new SPNavigationNode(ParentWeb.Title, ParentWeb.Url + "/default.aspx", true);

SPNavigationNode ChildNode = new SPNavigationNode(DChildWeb.Title, DChildWeb.Title + "/default.aspx");

ParentWeb.Navigation.TopNavigationBar.AddAsLast(ChildNode);

ChildWeb.Navigation.TopNavigationBar.AddAsFirst(ParentNode);

ChildWeb.Navigation.UseShared = true;

I know there’s should be an easier approach, just that I am too tired and lazy to explore any further as I have figured a lousy way of doing this. If anyone could throw more light on this, I’d really appreciate. Oh yes! I almost forgot… the above code snippet works very well. And know what, it also removes the top navigation if you delete the sub site!! Wow, that’s MOSS 2007! J