Search code examples
c#asp.netsql-serversubmenu

How to create submenu in html format from database?


<div id="menu">    
        <ul>
            <li><a href="#">HOME</a></li>
            <li><a href="#">ABOUT US</a></li>

        <li><a href="#">PRODUCTS/a>
            <ul>
            <li><a href="#">Product1</a></li>
            <li><a href="#">Product2</a></li>
            <li><a href="#">Product3</a></li>
            </ul>
        </li>               
    </ul>       

</div>

This is menu code and menu items are static and I want to display product1, product2, product3 dynamically from database


Solution

  • Easiest way i think could be using repeater control to bind multiple <li> tags from server side.

    You can use ajax call as well to bind at client if you don't want to post back to refresh the menu item.

    Code:

    May this will Help to get you the idea of one way of binding it from server side…..

    ASPX

    <ul>
                <li><a href="#">HOME</a></li>
                <li><a href="#">ABOUT US</a></li>
    
                <ul>
                    <asp:Repeater ID="_rptSubMenu" runat="server">
                        <ItemTemplate>
                            <li><a href="#"><%Eval(ProductId) %> </a>
                            </li>
                        </ItemTemplate>
                    </asp:Repeater>
    
    
                </ul>
            </ul>
    

    CS

    public partial class _Default : Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                bindMenu();
            }
    
            public void bindMenu()
            {
                //ADO Code to get menu Items from Database
                //You can load it directly form DataTable or you can create a LIST with Menu Entity as i have
    
    
                string connectionstring = "";
                List<MenuItem> lstMenu = new List<MenuItem>();
    
                SqlConnection con = new SqlConnection(connectionstring);
                SqlCommand cmd = new SqlCommand("SELECT Id,MenuName FROM TM_Menu", con);
                SqlDataReader dr;
    
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    lstMenu.Add(new MenuItem { ProductID = dr["Id"].ToString(), Name = dr["Name"].ToString() });
                }           
    
                _rptSubMenu.DataSource = lstMenu;
                _rptSubMenu.DataBind();
    
            }
        }
    
        public class MenuItem
        {
            public string ProductID { get; set; }
            public string Name { get; set; }
        }