Adding items to the end of a SiteMapPath
This question came up on the ASP.NET forums and I thought it was worth mentioning here. There are some instances when it would be useful to add an extra bit of detail to the end of a SiteMapPath. For example, lets say there is a MultiView on the page and you'd like the Path to look like:
Home >> Parent Page >> Current Page >> Current View
A SiteMapResolve event handler wouldn't really work here since we need intimate knowledge about the current page's controls. Here's a couple solutions.
The "cheater" way (easiest) :
<asp:SiteMapPath ID="SiteMapPath2" runat="server" PathSeparator=" | " >
<CurrentNodeTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Title") %>'></asp:Label>
<asp:Label ID="Label3" runat="server" Text='<%# SiteMapPath2.PathSeparator %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# MultiView1.GetActiveView().ID %>'></asp:Label>
</CurrentNodeTemplate>
</asp:SiteMapPath>
The "hack" (minimum code) :
Protected Sub SiteMapPath1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs)
Dim sep As New Literal()
sep.Text = SiteMapPath1.PathSeparator
Dim view As New Literal()
view.Text = MultiView1.GetActiveView().ID
SiteMapPath1.Controls.AddAt(-1, sep)
SiteMapPath1.Controls.AddAt(-1, view)
End Sub
The "nearly complete" (most involved) :
Protected Sub SiteMapPath1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs)
Dim sepItem As New SiteMapNodeItem(-1, SiteMapNodeItemType.PathSeparator)
Dim sepTemplate As ITemplate = SiteMapPath1.PathSeparatorTemplate
If sepTemplate Is Nothing Then
Dim separator As New Literal()
separator.Text = SiteMapPath1.PathSeparator
sepItem.Controls.Add(separator)
Else
sepTemplate.InstantiateIn(sepItem)
End If
sepItem.ApplyStyle(SiteMapPath1.PathSeparatorStyle)
Dim viewItem As New SiteMapNodeItem(-1, SiteMapNodeItemType.Current)
Dim viewName As New Literal()
viewName.Text = MultiView1.GetActiveView().ID
viewItem.Controls.Add(viewName)
viewItem.ApplyStyle(SiteMapPath1.CurrentNodeStyle)
SiteMapPath1.Controls.AddAt(-1, sepItem)
SiteMapPath1.Controls.AddAt(-1, viewItem)
End Sub
Each of these has some pros and cons. The primary trade off's are complexity vs integration with the SiteMapPath. Clearly the first two solutions don't take into account SeparatorTemplates. They also make it difficult to apply the controls styles to the new elements. However, even the nearly complete way won't be completely seamless with the SiteMapPath. Primarily the SiteMapPath merges NodeStyle and CurrentNodeStyle to create the style that actually gets applied to the CurrentNode (I'm assuming here that we'll just apply CurrentNodeStyle again). Since that merged style is internal and generated on the fly in SiteMapPath, we can't access it. However, this doesn't stop someone from applying their own styles through code and properties instead.
Two posts in one week! I'm on a roll.