ASP.NET - How to create dynamic menu links in asp.net

Asked By madhu krishna on 18-Jul-11 08:13 AM
i have to get dynamic menu links for my application home page  can any one send me the code or any web link?
Reena Jain replied to madhu krishna on 18-Jul-11 08:15 AM
Hi,

ust create xml file for menu and use following code

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
EnableMenu();
}
}

protected void EnableMenu()
{
DataSet ds = new DataSet();
DataRowView drPView;
DataRowView drCView;
ds.ReadXml(ConfigurationSettings.AppSettings["XMLFile"].ToString());
DataView dvParent = new DataView(ds.Tables[0]);
DataView dvChild = new DataView(ds.Tables[1]);
MenuItem oParentMenuItem = new MenuItem();
MenuItem oChildMenuItem = new MenuItem();

for (int i = 0; i < dvParent.Count; i++)
{
drPView = dvParent[i];
oParentMenuItem = new MenuItem(drPView.Row.ItemArray["MenuCaption"].ToString(), drPView.Row.ItemArray["ParentId"].ToString());
MenuContent.Items.Add(oParentMenuItem);
dvChild.RowFilter = "ParentId=" + drPView.Row.ItemArray["ParentId"].ToString();
for (int i = 0; i &lt; dvChild.Count; i++)
{
drCView = dvChild[i];
oChildMenuItem = new MenuItem(drCView.Row.ItemArray["MenuCaption"].ToString(), drCView.Row.ItemArray["ChildID"].ToString(), "", drCView.Row.ItemArray["MenuUrl"].ToString());
oParentMenuItem.Items.Add(oChildMenuItem);
}
}
}
here is some good link for this

Creating a floating html menu using jquery and css

http://net.tutsplus.com/tutorials/html-css-techniques/creating-a-floating-html-menu-using-jquery-and-css/ 

Slide menu using JQuery

http://www.codeproject.com/KB/scripting/JQuerySlideMenu.aspx

jquery menu

http://forums.asp.net/t/1583528.aspx

using site map

http://www.beansoftware.com/ASP.NET-Tutorials/Dynamic-Static-XML-Menus.aspx

hope this will help you

Web Star replied to madhu krishna on 18-Jul-11 08:16 AM

Dynamic Menu control is very useful in asp.net these are menu which you can see on every site, by menu control you can navigate from one page to another page.

Here i m creating menu using XML File,For your task you can create 2 xml file for spliting menu.

So follow these steps to create Dynamic Menu Control

The Steps are:

1- Start -> All Programs -> Visual Studio 2005 or Visual Studio 2008

2- Now go to File Menu -> New -> Web Site

3- Under Visual Studio Installed Template-> Choose ASP.NET WEB SITE -> Choose File System from the location combo box -> Set the path by the browse button - > Choose the language from the Language ComboBox (Visual C# , Visual Basic , J #)
Choose Visual C#

4 - Click on the OK Button:-

First you have to learn XML and HTML to work with ASP .NET_

I have used <! -  -> to make the text as comment this is the way to make comment in this code .

This is the Source Code window and in this page you will se this code.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Type your webpage title here</title>  <!- Here you can specify your page title in between title tag ->
</head>
<body>
<form id="form1? runat="server">
<div>
<!- In between div tags you can manage your web controls like buttons, labels, picture
Box, ImageMap etc ->

</div>
</form>
</body>
</html>

See here is a tab named Design in the bottom of this page

5- Click on this tab and you will see a blank web page where you can drag any control from the toolbox (which is in the left side of this window)

Open Web.config file and write true in place of false, See
  <compilation debug="true">

6- Drag a Menu Control from the navigation control tab

7-Now go in solution explorer and right click on the website and choose Add new item, select XML file
now again choose Add new item, select site Map .

8- Now open XML file and type this code in this.

<?xml version="1.0" encoding="utf-8" ?>
<application>

  <setction title="Section 1" value="default.aspx">
  <subpage title ="Page 1" value="page1.aspx"/>
  <subpage title ="Page 2" value="page2.aspx"/>
  <subpage title ="Page 3" value="page3.aspx"/>
  </setction>

  <setction title="Section 2" value="default.aspx">
  <subpage title ="Page 1" value="page1.aspx"/>
  <subpage title ="Page 2" value="page2.aspx"/>
  <subpage title ="Page 3" value="page3.aspx"/>
  </setction>

</application>

9- Now open your site Map file and type this code in it.

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

  <siteMapNode url= "Default.aspx" title= "Section 1"  description="">
  <siteMapNode url="Page1.aspx" title="Page 1"  description="" />
  <siteMapNode url="Page2.aspx" title="Page 2"  description="" />
  <siteMapNode url="Page3.aspx" title="Page 3"  description="" />
  </siteMapNode>
</siteMap>

10- In Design mode select menu control and click on the arrow (seems when you move cursor on menu control)

Choose Data Source -> choose XML or Site Map Data Source
 Ok

11 - Now run your web site by Ctrl + F5

Now you will get output.

Hope this will help you.

Jitendra Faye replied to madhu krishna on 18-Jul-11 08:19 AM

There are quite a few sources about how to create dynamic menus (menus that are not embedded in XAML or code, but rather loaded from an external file):

  1. Loose XAML - Using the http://weblogs.asp.net/controlpanel/blogs/msdn2.microsoft.com/en-us/library/system.windows.markup.xamlreader.aspx, one can load an external, non-pre-compiled fragment of XAML, much like the one presented here:
    <MenuItem
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    Header="_Simple">
    <MenuItem Header="1" />
    <MenuItem Header="2" />
    <MenuItem Header="3" />
    </
    MenuItem>
    The above fragment will then be loaded into the menu like so:
    using (FileStream looseXamlFile = File.OpenRead("Loose.xaml"))
    {
    this.mainMenu.Items.Insert(0,
    (MenuItem)XamlReader.Load(looseXamlFile));
    }
    And on the window, it will look like this:

    http://weblogs.asp.net/blogs/okloeten/WindowsLiveWriter/CreatingDynamicMenus_78D3/simple_2.png

    This is a very useful thing and you can read more about this method on http://blogs.microsoft.co.il/blogs/tamir/archive/2007/10/18/how-to-build-dynamic-menus-and-toolbars.aspx.
    However, this way, you are bound to the elements of the WPF schema and all errors that would have occurred in the past during compile-time, will now occur during run-time. These presents a hardship for the developer. The bigger problem is what happens when receiving the items for the menu from a different source, such as a list you wish to bind to, in which case, you simply can't use Loose XAML.
  2. Data Templates - This way is the most intuitive way to bind a list of items or, better yet, an unary tree of items to a GUI representation of them. For instance, we have a list of Item objects (a simple class with one property - Value) and wish to bind them to menu items.
    <MenuItem x:Name="dataTemplateMenu" Header="_Data Template" >
    <MenuItem.Resources>
    <DataTemplate DataType="{x:Type local:Item}">
    <MenuItem Header="{Binding Path=Value}" />
    </DataTemplate>
    </MenuItem.Resources>
    </
    MenuItem>
    The XAML described here takes each Item and represents it using a MenuItem. To load a list into the menu, we simply call:
    dataTemplateMenu.ItemsSource = itemArray;
    After this call, all of the items will have MenuItems created for them and will look like this:

    http://weblogs.asp.net/blogs/okloeten/WindowsLiveWriter/CreatingDynamicMenus_78D3/data.templates_2.png 

    Very nice, but something is wrong here. Yes, the items are extremely large. Hovering over one reveals that we have something inside that menu:

    http://weblogs.asp.net/blogs/okloeten/WindowsLiveWriter/CreatingDynamicMenus_78D3/data.templates.hover_2.png

    Hum. That looks familiar. It's the same size as a normal MenuItem... Oh, wait, that's because it really is one. This is because when you create a Data Template, the items that enter the tree are actually your user-defined objects (in this case, the Item class). Before applying the template, the menu item asks the object about to be inserted into it whether it can be visually displayed. Because Item has no visual representation, the process creates a MenuItem to hold it, thus creating two menu items (the one automatically created and the one created using the Data Template).
  3. Item Container Style - So after two ways that didn't work well for us, the one that will is the MenuItem's http://weblogs.asp.net/controlpanel/blogs/msdn2.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemcontainerstyle.aspx. This way, all you do is simply define a style for all of the menu items that will be placed under a certain menu item and use binding to bind those items to the values of your objects' properties:
    <MenuItem x:Name="itemContainerStyleMenu" Header="_Item Container Style">
    <MenuItem.ItemContainerStyle>
    <Style TargetType="{x:Type MenuItem}">
    <Setter Property="Header" Value="{Binding Path=Value}" />
    </Style>
    </MenuItem.ItemContainerStyle>
    </
    MenuItem>

    Then you set the source:
    itemContainerStyleMenu.ItemsSource = itemArray;
    and presto:

    http://weblogs.asp.net/blogs/okloeten/WindowsLiveWriter/CreatingDynamicMenus_78D3/item.container.style_2.png

    We now have what we needed.

    Extra: Recursive hierarchy could also be achieved using:
    1. Placing the style in the resources of a window, the application, etc. with a key.
    2. A setter of ItemsSource that binds to the collection of child items.
    3. A setter of ItemContainerStyle that will point to the style's key.

The source for this article is available http://weblogs.asp.net/blogs/okloeten/WindowsLiveWriter/CreatingDynamicMenus_78D3/WpfApplication1.zip.

Devil Scorpio replied to madhu krishna on 18-Jul-11 08:22 AM
Hi Madhu,

You can use MENU control for that and easily add menu items in that at run time like;

MenuItem mu = new MenuItem();
mu.Text = TextBox1.text;
mu.NavigateUrl = TextBox1URL.text;
Menu1.Items.Add(mu);

MenuItem mu1 = new MenuItem();
mu1.Text = TextBox2.text;
mu1.NavigateUrl = TextBox2URL.text;
Menu1.Items.Add(mu1);


Kalit Sikka replied to madhu krishna on 18-Jul-11 08:27 AM
REFER: http://aspalliance.com/822

<
asp:Menu ID="menu"DataSourceID="xmlDataSource" runat="server"  BackColor="#FFFBD6"DynamicHorizontalOffset="2" Font-Names="Verdana"  ForeColor="#990000"StaticSubMenuIndent="10px" StaticDisplayLevels="1" > <DataBindings>   <asp:MenuItemBindingDataMember="MenuItem" NavigateUrlField="NavigateUrl"   TextField="Text" ToolTipField="ToolTip"/> </DataBindings> <StaticSelectedStyleBackColor="#FFCC66" /> <StaticMenuItemStyleHorizontalPadding="5px" VerticalPadding="2px" /> <DynamicMenuStyle BackColor="#FFFBD6"/> <DynamicSelectedStyleBackColor="#FFCC66" /> <DynamicMenuItemStyle HorizontalPadding="5px"VerticalPadding="2px" /> <DynamicHoverStyleBackColor="#990000" Font-Bold="False"ForeColor="White"/> <StaticHoverStyle BackColor="#990000"Font-Bold="False" ForeColor="White" /> </asp:Menu> <asp:XmlDataSource ID="xmlDataSource"TransformFile="~/TransformXSLT.xsl"   XPath="MenuItems/MenuItem"runat="server"/>

Now it is time to retrieve and begin formatting the menu data for use by Microsoft's menu.  The challenge is to establish parent child relationships and then create a hierarchical representation of the data.   A DataSet object is perfect for this because it can store the structure of an entire database, including relationships, and then convert that relational data into nested XML. 

Add the following C# code to your Page_Load method.  This code uses a DataAdapter to retrieve data from the single database table and to fill a DataSet.  Once filled, a DataRelation is applied to the DataSet to establish MenuID and ParentID dependencies.  Finally, a call to GetXML() retrieves a hierarchical XML representation of all relational data within the dataset.  

Listing 3 - The C# Code

using System; using System.Xml; using System.Data; using System.Data.SqlClient;   public partial class _Default:System.Web.UI.Page {   protected void Page_Load(object sender,EventArgs e)   {   DataSet ds = new DataSet();   string connStr = "server=localhost;Trusted_Connection=true;database=MenuDb";   using(SqlConnection conn = newSqlConnection(connStr))   {     string sql = "Select MenuID, Text,Description, ParentID from Menu";     SqlDataAdapter da = newSqlDataAdapter(sql, conn);     da.Fill(ds);     da.Dispose();   }   ds.DataSetName = "Menus";   ds.Tables[0].TableName = "Menu";   DataRelation relation = newDataRelation("ParentChild",    ds.Tables["Menu"].Columns["MenuID"],    ds.Tables["Menu"].Columns["ParentID"], true);     relation.Nested = true;   ds.Relations.Add(relation);     xmlDataSource.Data = ds.GetXml();     if (Request.Params["Sel"] != null)     Page.Controls.Add(newSystem.Web.UI.LiteralControl("You selected " +     Request.Params["Sel"]));   } }
Riley K replied to madhu krishna on 18-Jul-11 08:43 AM
You can set  XMLDataSource for Asp.Net Menu

here in the below code i am creating a  XMLDataSource from database


Dim ds As New DataSet()
xmlDataSource.EnableCaching = False
Using c.con
Dim sql As String = "Select id,menu_name,menu_ParentID,menu_NavigateUrl from user_menus where menu_accessto='" & Session("role") & "' and user_id='" & Session("uid") & "' order by menu_sequence"
Dim da As New SqlDataAdapter(sql, c.con)
da.Fill(ds)
da.Dispose()
End Using
ds.DataSetName = "Menus"
ds.Tables(0).TableName = "user_menus"
Dim relation As New DataRelation("ParentChild", ds.Tables("user_menus").Columns("id"), ds.Tables("user_menus").Columns("menu_ParentID"), True)
relation.Nested = True
ds.Relations.Add(relation)
xmlDataSource.Data = ds.GetXml()

Radhika roy replied to madhu krishna on 18-Jul-11 12:53 PM
Follow this example , here i am creating menu using xml file.

xml file-

<?xml version="1.0" encoding="utf-8" ?>
<siteMap>
 <siteMapNode url="Default.aspx" title="Home">
   <siteMapNode title="Products" description="Our Products">
    <siteMapNode url="Product1.aspx" title="My Products" 
      description="These are my products" />
    <siteMapNode url="Product2.aspx" title="New Products" 
      description="Some new products " />
   </siteMapNode>
   <siteMapNode title="Services" description="Our Services">
    <siteMapNode url="Service1.aspx" title="http://asp.net/ Consulting"
      description="Best http://asp.net/ Consulting" />
    <siteMapNode url="Service2.aspx" title="http://asp.net/ Training" 
      description="Best http://asp.net/ Training" />
   </siteMapNode>
 </siteMapNode>
</siteMap>

Now use this code to design menu using xml.

private void CreateMenuWithXmlFile()
{
  string path = @"C:\MyXmlFile.xml";
  DataSet ds = new DataSet();
  ds.ReadXml(path);
  Menu menu = new Menu();
  menu.MenuItemClick += new MenuEventHandler(menu_MenuItemClick);

  for (int i = 0; i < ds.Tables.Count; i++)
  {
    MenuItem parentItem = new MenuItem((string)ds.Tables[i].TableName);
    menu.Items.Add(parentItem);

    for (int c = 0; c < ds.Tables[i].Columns.Count; c++)
    {
    MenuItem column = new MenuItem((string)ds.Tables[i].Columns[c].ColumnName);
    menu.Items.Add(column);

    for (int r = 0; r < ds.Tables[i].Rows.Count; r++)
    {
      MenuItem row = new MenuItem((string)ds.Tables[i].Rows[r][c].ToString());
      parentItem.ChildItems.Add(row);
    }
    }
  }

  Panel1.Controls.Add(menu);
  Panel1.DataBind();
}

follow this link also-

http://www.codeproject.com/KB/menus/PopulatingMenuControlASP2.aspx

Hope this will help you.