Using CAML to add Web Parts to an existing page

Posted Monday, September 15, 2008 4:04 PM by CoreyRoth

In the past when I thought of how to do this, I tended to over analyze it a bit.  I always assumed there was something special in how you do this, but in reality, it is not much different than adding web parts to a new page.  I am not sure if this is the best way to do it and it only works in some cases, but it's a start and maybe somebody else can help out.  The main thing I was trying to avoid was having to write code in a feature receiver to accomplish this.  In today's example, we are going to assume I have a page called default.aspx on a site and it has a web part zone called Left (like many default page templates do).  To make this happen, I basically write CAML that is just like if I was creating a new page.  This includes getting a copy of a default.aspx page (any one will do that has similar names for web part zones) into a new feature.  In this case, I am using the default.aspx file from the STS site template located at 12\TEMPLATE\SiteTemplates\sts.  In my elements file, I start by adding a Module and File block like below.

<Module Name="DWS" Url="" Path="dws">

  <File Url="default.aspx" IgnoreIfAlreadyExists="TRUE">

The module Name you specify is DWS (which I believe is the name of the list that pages are stored in).  The Path is specified as dws as well assuming I stored my local default.aspx in a folder of that name.  You can choose to use a path or not.  It shouldn't matter.  I then specify the filename with the IgnoreIfAlreadyExists attribute set to true.  I believe this results in SharePoint not trying to create a new page if one of that name already exists.  After you have your file element it is just a matter of specifying your web parts as usual.

<AllUsersWebPart WebPartZoneID="Left" WebPartOrder="1">


              <WebPart xmlns="">

                  <Assembly>Microsoft.Office.Server.Search, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>












Every time the feature is activated, it will add the web parts you specify to the file that you specify.  This ends up working pretty well, but keep in mind there is nothing built in to delete your web parts off of your web page.  If you want to do that, you are going to have to write code in a feature receiver to remove the web parts (a post which I still need to write).  Anyhow, I guess what I am saying is that it really isn't any more complicated than adding web parts to a new page.  I am not sure if this is the best way to do it so if you have a better idea be sure to leave a comment.

Filed under: , ,


No Comments

Leave a Comment