How to bind SiteMap to a dynamically created TreeView?
Asked Answered
A

1

5

How to bind SiteMap to a dynamically created TreeView at runtime?

Andry answered 2/8, 2009 at 11:1 Comment(0)
B
11

There are a couple of ways to do this.

Put a PlaceHolder on the page:

  <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

Now create a TreeView and assign a SiteMapDataSource that is already on the page:

  //Code Behind
  TreeView tv1 = new TreeView();
  tv1.DataSourceID = "SiteMapDataSource1";
  PlaceHolder1.Controls.Add(tv1);

  //aspx
  <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />

Or you can assign the SiteMap programmatically:

  // Create an instance of the XmlSiteMapProvider class.
  XmlSiteMapProvider testXmlProvider = new XmlSiteMapProvider();
  NameValueCollection providerAttributes = new NameValueCollection(1);
  providerAttributes.Add("siteMapFile", "Web2.sitemap");

  // Initialize the provider with a provider name and file name.
  testXmlProvider.Initialize("testProvider", providerAttributes);

  // Call the BuildSiteMap to load the site map information into memory.
  testXmlProvider.BuildSiteMap();

  SiteMapDataSource smd = new SiteMapDataSource();
  smd.Provider = testXmlProvider;

  TreeView tv2 = new TreeView();
  tv2.DataSource = smd;
  tv2.DataBind(); //Important or all is blank
  PlaceHolder1.Controls.Add(tv2);

Setting the SiteMap programmatically also allows you to switch files based on business rules.

This can also be done via the Web.Config:

  <configuration>
  <!-- other configuration sections -->
    <system.web>
     <!-- other configuration sections -->
     <siteMap>
       <providers>
        <add name="SiteMap1" type="System.Web.XmlSiteMapProvider" siteMapFile="~/Web.sitemap" />
        <add name="SiteMap2" type="System.Web.XmlSiteMapProvider" siteMapFile="~/Web2.sitemap" />
       </providers>
    </siteMap>
   </system.web>
  </configuration>

and then in your aspx page just switch provider:

<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" SiteMapProvider="SiteMap2"  />

Hope this helps

Biagio answered 6/8, 2009 at 11:16 Comment(2)
Unfortunately, you still have to save the sitemap to a file.Earwax
Yep by default there needs to be a sitemap file. You can however implement your own SiteMapProvider that could return a dynamically generated sitemap: msdn.microsoft.com/en-us/library/aa479033.aspx - msdn.microsoft.com/en-us/library/aa479320.aspx. If you Google "custom sitemapprovider" there are plenty of posts about it.Biagio

© 2022 - 2024 — McMap. All rights reserved.