How to select a SiteMapNode from sitemap using code behind?

2.4k Views Asked by At

I am busy working building my own custom navigation page in ASP.Net. I'm busy trying to fill an <asp:Repeater>'s data with a specific SiteMapNode from my web.sitemap file.

Here is my web.sitemap:

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
    <siteMapNode roles="*">
        <siteMapNode url="~/Secure/Home" title="Home">
            <!-- Home SiteMapNodes -->
        </siteMapNode>
        </siteMapNode url="~/Secure/Maintenance title="maintenance">
            <!-- Maintenance SiteMapNodes -->
        </siteMapNode>
    </siteMapNode>
</siteMap>

In my Home navigation page I have the following repeater set up:

<ul>
    <asp:Repeater runat="server" ID="rptMenu" DataSourceID="smdsMain" OnItemDataBound="rptMenu_ItemDataBound">
        <ItemTemplate>
            <li>
                <a runat="server" href='<%# Eval("url") %>'>
                    <%# Eval("title") %>
                </a>
            </li>
        </ItemTemplate>
    </asp:Repeater>
</ul>
<asp:SiteMapDataSource ID="smdsMain" runat="server" ShowStartingNode="false" SiteMapProvider="XmlSiteMapProvider" />

I'm attempting to fill the <asp:Repeater> in the code behind using the OnItemDataBound method like this:

protected void rptMenu_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    SiteMapNode homeNode = ???;
    ((Repeater)e.Item.FindControl("rptMenu")).DataSource = homeNode;
    ((Repeater)e.Item.FindControl("rptMenu")).DataBind();
}

My only question is how to I set the homeNode SiteMapNode to the SiteMapNode with the title home?

1

There are 1 best solutions below

0
Barry Michael Doyle On BEST ANSWER

After some chopping and changing and a bit of research I came to a solution using the SiteMap.Provider.FindMapNodeFromKey(key) method. Where key is the url of the web.sitemap node.

I also realized that I shouldn't be using the OnItemDataBound method to set my rptMenu's DataSource. So I did in the the Page_Load method.

As a result, here is my working Page_Load code:

var homeNode = SiteMap.Provider.FindSiteMapNodeFromKey("~/Secure/Maintenance");
rptMenu.DataSource = homeNode.ChildNodes;
rptMenu.DataBind();