Jules
Jules

Reputation: 4339

How to change the rendering of a Menu Item in ASP.NET 4

Instead of rendering the image of a menu item as an <img> tag within an anchor, I'd like to add a class to the anchor tag which adds the image as a background image.

At the moment, I'm doing some post-processing with javascript that searches for image urls. If found, they are removed and replaced with a CSS class.

Is there a way to perform this by overriding the Menu or implementing a MenuAdapter?
I've had a look at the MenuAdapter class but it looks like I'd have to re-implement all rendering functionality just to change this small part.

[Note: the reason I'm doing this is because I want to display the images after the text; i struggled to do this using the default rendering.]

ETA: Answered below.

Upvotes: 0

Views: 1180

Answers (1)

Jules
Jules

Reputation: 4339

I found the simplest way is to override the Render method of the Menu.

Using this menu, you can put a tooltip and css class, separated by a semi-colon, in the ToolTip property of the menu item:
item.ToolTip = "this is the tip; class1 class2";

Note: This is a simplistic menu that performs as much as I want it to do. It ignores ImageUrl and SeparatorImageUrl.

public class CSSItemMenu : Menu
    {

        protected override void Render(HtmlTextWriter writer)
        {
            this.PerformDataBinding();

            writer.Write(string.Format("<div id=\"{0}\" class=\"{1}\">", base.ClientID, base.CssClass));
            writer.WriteLine();
            writer.WriteLine("<ul class=\"level1\">");

            foreach (MenuItem item in Items)
            {
                WriteItem(writer, item, 1);
            }

            writer.WriteLine("</ul>");
            writer.WriteLine("</div>");
        }

        private static void WriteItem(HtmlTextWriter writer, MenuItem item, int level)
        {
            writer.WriteLine("<li>");

            string title = "";
            var userClass = "";
            if (!string.IsNullOrEmpty(item.ToolTip))
            {
                var data = item.ToolTip.Split(';');
                title = string.Format(" title=\"{0}\"", data[0].Trim());
                if (data.Length > 1)
                {
                    userClass = " " + data[1].Trim();
                }
            }
            var cssClass = string.Format("class = \"popout level{0}{1}\"", level, userClass);

            writer.WriteLine(string.Format("<a {0} href=\"{1}\"{2}>{3}</a>", cssClass, item.NavigateUrl, title, item.Text));

            if (item.ChildItems.Count > 0)
            {
                writer.WriteLine(string.Format("<ul class=\"level{0}\">", level + 1));
                foreach (MenuItem child in item.ChildItems)
                {
                    WriteItem(writer, child, level + 1);
                }
                writer.WriteLine("</ul>");
            }

            writer.WriteLine("</li>");
        }

    }

Upvotes: 3

Related Questions