Reputation: 287
<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
Upvotes: 2
Views: 1171
Reputation: 56
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; }
}
Upvotes: 1
Reputation: 1
try something like this.. my data base is ms sql so we might be different on the code of retrieving the data on 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>
<?php
$sqli = "select item from Rroducts ";
$stmt = sqlsrv_query( $conn, $sqli );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$item= $row[' item'];
echo "<li><a href='#'>".$item."</a></li>";
}
sqlsrv_free_stmt( $stmt2;
?>
</ul>
</li>
</ul>
Upvotes: 0