Search code examples
c#asp.nethtmlvisual-studio-2010htmlgenericcontrol

make dynamically generated href call a c# function


I am trying to build a dropdown as below.

this is the menu that I need to generate

I am generating html ul & li tags as below and works fine. However, everytime there is an anch tag (see the in-line comment); I need to be able to call a function and pass a text that was clicked. How can I do this?

        foreach (var productType in productTypesNames.Keys)
        {
            var li = new HtmlGenericControl("li");
            nav.Controls.Add(li);
            var ul = new HtmlGenericControl("ul");

            var anchor = new HtmlGenericControl("a");
            anchor.Attributes.Add("href", "#");

            foreach (var pName in productTypesNames[productType] )
            {
                var subLi = new HtmlGenericControl("li");
                var anch = new HtmlGenericControl("a");
                anch.Attributes.Add("href", "#");
                //**THIS NEEDS TO CALL A C# FUNCTION AND PASS pName; instead of #**
                anch.InnerHtml = pName;
                subLi.Controls.Add(anch);
                ul.Controls.Add(subLi);
            }
            anchor.InnerHtml = productType;
            li.Controls.Add(anchor);
            li.Controls.Add(ul);
        }

Solution

  • If you don't mind a postback, or want it, use a LinkButton control, easily built dynamically instead of your HtmlGenericControl("a"), and have the server-side onclick method call your other method.

    Otherwise you need AJAX as others have explained.