If you want to change the way items are displayed in the control, you can use the StaticMenuItemTemplate
and DynamicMenuItemTemplate
. I will use only the first in my example (static, for top-level elements):
<asp:Menu runat="server" ...> <StaticMenuItemTemplate> <a id="<%# GetSuitableClientId(Container) %>"><%# Eval("Text") %></a> </StaticMenuItemTemplate> </asp:Menu>
The StaticMenuItemTemplate
property is of type ITemplate
and, as is often the case with such template properties, it is decorated with the TemplateContainer
attribute. This indicates the container into which the template should be created, usually the container provides access to some context that may be needed during rendering. In this case, it is of type MenuItemTemplateContainer
, which implements IDataContainer
and thus gives access to the data item.
So, we pass this container back to the method on our page, and in this method we create the identifier that we consider necessary. We could use a data element for depth and a container for an index, for example:
protected string GetSuitableClientId(MenuItemTemplateContainer container) { MenuItem item = (MenuItem)container.DataItem; return String.Format("menuItem-{0}-{1}", item.Depth, container.ItemIndex); }
My guess in constructing this answer is that you can now configure JavaScript to bind to click events on the <a id="menuItem-2-4">Text</a>
element, since now you have predictable identifiers on client side.
Edit: you can also use the following inside your template and let ASP.NET take care of creating a unique identifier on the client side, but this is less predictable ...
<asp:HyperLink ID="MenuItem" runat="server" NavigateUrl='<%# Eval("NavigateUrl") %>' />
source share