PDA

View Full Version : Dynamic Menu



RCN
Feb 04, 2015, 2:10 AM
Ulisses (@ucaneto), asked me a sample of dynamic menu and i would like to share it

Related thread: http://forums.ext.net/showthread.php?33821



<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
Dictionary<int, List<MenuDefinition>> dicGrouped = (from md in LoadFromDatabase()
orderby md.Order ascending
group md by md.ParentID.HasValue ? md.ParentID.Value : 0 into grouping
select grouping).ToDictionary(grouping => grouping.Key, grouping => grouping.ToList());


IList<Ext.Net.MenuItem> lstMenu = Process(0, dicGrouped);

if (lstMenu != null)
{
_root.Items.AddRange(lstMenu);
}
}
}

/// <summary>
/// Simulates the load of records from database
/// </summary>
/// <returns></returns>
public IList<MenuDefinition> LoadFromDatabase()
{
return new List<MenuDefinition>
{
new MenuDefinition { ID = 1, Name = "Item 1", Order = 1, Icon = Icon.FlagAd },
new MenuDefinition { ID = 2, Name = "Item 2", Order = 2, Icon = Icon.FlagAe },
new MenuDefinition { ID = 3, Name = "Item 3", ParentID = 1, Order = 1, Icon = Icon.FlagAf },
new MenuDefinition { ID = 4, Name = "Item 4", ParentID = 3, Order = 1, Icon = Icon.FlagAg },
new MenuDefinition { ID = 5, Name = "Item 5", ParentID = 4, Order = 1, Icon = Icon.FlagAi },
new MenuDefinition { ID = 6, Name = "Item 6", ParentID = 3, Order = 2, Icon = Icon.FlagAl },
new MenuDefinition { ID = 7, Name = "Item 7", ParentID = 2, Order = 1, Icon = Icon.FlagAm },
new MenuDefinition { ID = 8, Name = "Item 8", ParentID = 7, Order = 1, Icon = Icon.FlagAn },
new MenuDefinition { ID = 9, Name = "Item 9", ParentID = 2, Order = 2, Icon = Icon.FlagAo },
};
}

public IList<Ext.Net.MenuItem> Process(int parentID, Dictionary<int, List<MenuDefinition>> dicGrouped)
{
IList<Ext.Net.MenuItem> lstLevel = null;

if (dicGrouped.ContainsKey(parentID))
{
lstLevel = new List<Ext.Net.MenuItem>();

foreach (MenuDefinition rdm in dicGrouped[parentID])
{
Ext.Net.MenuItem mniCurrent = new Ext.Net.MenuItem
{
Text = rdm.Name,
Icon = rdm.Icon.HasValue ? rdm.Icon.Value : Icon.None
};

lstLevel.Add(mniCurrent);

IList<Ext.Net.MenuItem> lstDescendants = Process(rdm.ID, dicGrouped);

if (lstDescendants != null)
{
Ext.Net.Menu mnuDescendants = new Ext.Net.Menu();

mnuDescendants.Items.AddRange(lstDescendants);

mniCurrent.Menu.Add(mnuDescendants);
}
}
}
return lstLevel;
}

public class MenuDefinition
{
public int ID { get; set; }

public string Name { get; set; }

public Nullable<int> ParentID { get; set; }

public int Order { get; set; }

public Nullable<Icon> Icon { get; set; }
}
</script>
<!DOCTYPE html>
<html>
<head runat="server">
</head>
<body>
<ext:ResourceManager ScriptMode="Debug" Locale="en" runat="server" />
<ext:Menu ID="_root" Floating="false" Layout="HBoxLayout" ShowSeparator="false" Cls="horizontal-menu" runat="server">
<Defaults>
<ext:Parameter Name="MenuAlign" Value="tl-bl?" Mode="Value" />
</Defaults>
</ext:Menu>
</body>
</html>