In this article I will explain with an example, how to build a
Database driven Twitter
Bootstrap Responsive
ASP.Net Menu control i.e.
ASP.Net Menu control that works for
Mobile Phone,
Tablet and
Desktop displays.
The
ASP.Net Menu control items will be dynamically populated from database using C# and VB.Net.
Database
I have made use of the following table Menus with the schema as follows.
I have already inserted few records in the table.
Note: You can have as many child levels as you want, this article uses 2 Level Menu structure.
Following is the
SiteMap, it has the following page structure.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The
Menu control is placed inside the
Bootstrap Menu and its following properties are set in order to make it
Responsive.
1. Orientation – Horizontal.
2.
RenderingMode – List. This makes the menu render as an
HTML List.
3.
StaticMenuStyle-CssClass – The
Bootstrap classes i.e.
nav and
navbar-nav are set.
4.
DynamicMenuStyle-CssClass - The
Bootstrap class
dropdown-menu is set.
<link rel="stylesheet" href='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css'
media="screen" />
<script type="text/javascript" src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js'></script>
<script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js'></script>
<div class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"
aria-expanded="false">
<span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span><span
class="icon-bar"></span><span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">ASPSnippets</a>
</div>
<div class="collapsenavbar-collapse" id="bs-example-navbar-collapse-1">
<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal" RenderingMode="List"
IncludeStyleBlock="false" StaticMenuStyle-CssClass="nav navbar-nav" DynamicMenuStyle-CssClass="dropdown-menu">
</asp:Menu>
</div>
</div>
</div>
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Populating the ASP.Net Menu control items from database
The PopulateMenu method is a recursive function. Inside the Page Load event of the Master Page, the Menu control is populated with the records from the Menus table.
Inside the
PopulateMenu method, a loop is executed over the
DataTable and if the
ParentMenuId is 0 i.e. the menu is a parent (root) menu, again a query is executed over the
Menus table to populate the corresponding submenus and again the
PopulateMenu method is called.
This process continues until all menus along with their
submenus are added to the
ASP.Net Menu control.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = this.GetData(0);
PopulateMenu(dt, 0, null);
}
}
private DataTable GetData(int parentMenuId)
{
string query = "SELECT [MenuId], [Title], [Description], [Url] FROM [Menus] WHERE ParentMenuId = @ParentMenuId";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
DataTable dt = new DataTable();
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Parameters.AddWithValue("@ParentMenuId", parentMenuId);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
private void PopulateMenu(DataTable dt, int parentMenuId, MenuItem parentMenuItem)
{
string currentPage = Path.GetFileName(Request.Url.AbsolutePath);
foreach (DataRow row in dt.Rows)
{
MenuItem menuItem = new MenuItem
{
Value = row["MenuId"].ToString(),
Text = row["Title"].ToString(),
NavigateUrl = row["Url"].ToString(),
Selected = row["Url"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
};
if (parentMenuId == 0)
{
Menu1.Items.Add(menuItem);
DataTable dtChild = this.GetData(int.Parse(menuItem.Value));
PopulateMenu(dtChild, int.Parse(menuItem.Value), menuItem);
}
else
{
parentMenuItem.ChildItems.Add(menuItem);
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not Me.IsPostBackThen
Dim dt As DataTable = Me.GetData(0)
PopulateMenu(dt, 0, Nothing)
End If
End Sub
Private Function GetData(parentMenuId As Integer) As DataTable
Dim query As String = "SELECT [MenuId], [Title], [Description], [Url] FROM [Menus] WHERE ParentMenuId = @ParentMenuId"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Dim dt As New DataTable()
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.Parameters.AddWithValue("@ParentMenuId",parentMenuId)
cmd.CommandType = CommandType.Text
cmd.Connection = con
sda.SelectCommand = cmd
sda.Fill(dt)
End Using
End Using
Return dt
End Using
End Function
Private Sub PopulateMenu(dt As DataTable, parentMenuId As Integer,parentMenuItem As MenuItem)
Dim currentPage As String = Path.GetFileName(Request.Url.AbsolutePath)
For Each row As DataRow In dt.Rows
Dim menuItem As New MenuItem()With { _
.Value = row("MenuId").ToString(), _
.Text = row("Title").ToString(), _
.NavigateUrl = row("Url").ToString(), _
.Selected = row("Url").ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase) _
}
If parentMenuId = 0 Then
Menu1.Items.Add(menuItem)
Dim dtChild As DataTable = Me.GetData(Integer.Parse(menuItem.Value))
PopulateMenu(dtChild, Integer.Parse(menuItem.Value), menuItem)
Else
parentMenuItem.ChildItems.Add(menuItem)
End If
Next
End Sub
Making the ASP.Net Menu Responsive using Bootstrap
The following script needs to be placed below the
ASP.Net Menu control. The following script removes the default functionality of the
ASP.Net Menu control and applies the
Bootstrap CSS classes to make it Responsive.
<script type="text/javascript">
//Disable the default MouseOver functionality of ASP.Net Menu control.
Sys.WebForms.Menu._elementObjectMapper.getMappedObject = function () {
return false;
};
$(function () {
//Remove the style attributes.
$(".navbar-nav li, .navbar-nav a, .navbar-navul").removeAttr('style');
//Apply the Bootstrap class to the SubMenu.
$(".dropdown-menu").closest("li").removeClass().addClass("dropdown-toggle");
//Apply the Bootstrap properties to the SubMenu.
$(".dropdown-toggle").find("a").eq(0).attr("data-toggle", "dropdown").attr("aria-haspopup", "true").attr("aria-expanded", "false").append("<span class='caret'></span>");
//Apply the Bootstrap "active" class to the selected Menu item.
$("a.selected").closest("li").addClass("active");
$("a.selected").closest(".dropdown-toggle").addClass("active");
});
</script>
Screenshots
Desktop display
Mobile display
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads