Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to change the way items in the control are rendered, you can use the <code>StaticMenuItemTemplate</code> and <code>DynamicMenuItemTemplate</code> properties. I will only use the first in my example (static, for top-level items):</p> <pre><code>&lt;asp:Menu runat="server" ...&gt; &lt;StaticMenuItemTemplate&gt; &lt;a id="&lt;%# GetSuitableClientId(Container) %&gt;"&gt;&lt;%# Eval("Text") %&gt;&lt;/a&gt; &lt;/StaticMenuItemTemplate&gt; &lt;/asp:Menu&gt; </code></pre> <p>The <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.menu.staticitemtemplate.aspx" rel="nofollow"><code>StaticMenuItemTemplate</code></a> property is of type <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.itemplate.aspx" rel="nofollow"><code>ITemplate</code></a> and as is often the case with such template properties it is decorated with the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontainerattribute.aspx" rel="nofollow"><code>TemplateContainer</code></a> attribute. This specifies the container in which the template is to be instantiated, usually the container gives access to some context that you may need in rendering. In this case it is of type <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.menuitemtemplatecontainer.aspx" rel="nofollow"><code>MenuItemTemplateContainer</code></a> which implements <code>IDataContainer</code> and thus gives access to the data item.</p> <p>So we pass this container back to a method in our page, and in that method we construct an ID as we see fit. We could use the data item for depth, and the container for the index for instance:</p> <pre><code>protected string GetSuitableClientId(MenuItemTemplateContainer container) { MenuItem item = (MenuItem)container.DataItem; return String.Format("menuItem-{0}-{1}", item.Depth, container.ItemIndex); } </code></pre> <p>My guess in constructing this answer is that you can now adjust your JavaScript to bind to click events on the <code>&lt;a id="menuItem-2-4"&gt;Text&lt;/a&gt;</code> element since you now have predictable client-side IDs. </p> <p>Edit: you can also use the following inside your template and let the ASP.NET take care of creating the unique client-side ID, but that is less predictable...</p> <pre><code>&lt;asp:HyperLink ID="MenuItem" runat="server" NavigateUrl='&lt;%# Eval("NavigateUrl") %&gt;' /&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload