Tạo Responsive Menu sử dụng Twitter Bootstrap trong Asp.net
(Sử dụng Twitter Bootstrap để tạo Responsive Menu) – Responsive Web Design là xu hướng thiết kế và phát triển web để đáp ứng mọi thiết bị và môi trường của người dùng theo các tiêu chí kích thước và chiều của màn hình thiết bị. Chính điều này sẽ tránh việc phải thiết kế nhiều giao diện khác nhau cho những thiết bị khác nhau và nó sẽ làm giảm thiểu thời gian cũng như chi phí thiết kế web. Bài viết dưới đây sẽ hướng dẫn các bạn xây dựng hệ thống Responsive Menu động đa cấp, các mục được lấy từ CSDL SQL Server và sử dụng thư viện Twitter Bootstrap.- B1: Tạo CSDL SQL NavigationMenu
- B2: Tạo Bảng Menu có cấu trúc phía dưới trong CSDL SQL Server.
STT | Tên trường | Kiểu trường | Ghi chú |
1 | MenuID | Int | Trường tự tăng |
2 | ParentID | Int | |
3 | MenuName | nvarchar(150) | Tên Menu |
4 | Description | nvarchar(250) | Mô tả |
5 | URL | nvarchar(200) | Đường dẫn Menu |
6 | MenuOrder | Int | Thứ tự sắp xếp |
7 | IsVisible | bit | Ân/Hiện Menu |
- B3: Nhập dữ liệu cho bảng Menu
Chú ý: Bạn có thể sử dụng nhiều cấp trong bảng Menu này, đối với Menu cấp 1 thì trường ParentID là Null hoặc -1.
- B4: Tạo stored procedure trong SQL Server
CREATE procedure
[dbo].[Pro_Menu_List]
@ItemID int,
@IsVisible bit
as
declare
@strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'Select * from Menu'
set @strWhere =' where 1=1'
if @ItemID=-1
set @strWhere= @strWhere +' and (ParentID=-1 Or
ParentID Is Null)'
if @ItemID<>-1
set @strWhere= @strWhere +' and ParentID='+ convert(nvarchar,@ItemID)
if @IsVisible=0
set @strWhere= @strWhere +' and (IsVisible=0 Or
IsVisible Is Null)'
set @strOrder =' Order by MenuOrder,
MenuName'
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
- B5: Tạo Project trong Microsoft Visual Studio 2010
Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.
Imports System.Data.SqlClient
Imports System.Data
Namespace ResponsiveNavigationMenuUsingBootstrap
Public Class SqlDataProvider
#Region "Membres
Prives"
Shared _IsError As Boolean = False
Private _connectionString As
String
#End Region
#Region "Constructeurs"
Public Sub New()
Try
_connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
_IsError = False
Catch ex As Exception
_IsError = True
End Try
End Sub
#End Region
#Region "Proprietes"
Public ReadOnly Property ConnectionString() As
String
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public Function
FillTable(ByVal sql As
String) As DataTable
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(sql,
_connectionString)
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
Public Function
FillTable(ByVal ProcName As String, ByVal ParamArray
Para() As ObjectPara)
As DataTable
Try
Dim tb As
New DataTable
Dim adap As
New SqlDataAdapter(ProcName,
_connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
If Not
Para Is Nothing
Then
For
Each p As ObjectPara In Para
adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
End If
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
#End Region
End Class
Public Class ObjectPara
Dim _name As String
Dim _Value As Object
Sub New(ByVal Pname As String, ByVal PValue As Object)
_name = Pname
_Value = PValue
End Sub
Public Property
Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property
Value() As Object
Get
Return _Value
End Get
Set(ByVal value As Object)
_Value = value
End Set
End Property
End Class
End Namespace
- B6: Download file jquery.min.js và bootstrap.min.js, tạo thư mục Js trong Project và Copy 2 file này vào thư mục Js.
- B7: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ Page Title="Responsive Navigation Menu using Twitter Bootstrap" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="ResponsiveNavigationMenuUsingBootstrap._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
<style type="text/css">
.container {
width: 100%;
}
.container {
padding-right: 2px;
padding-left: 2px;
margin-right: auto;
margin-left: auto;
}
</style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h1>
Responsive Navigation Menu using Twitter Bootstrap
</h1>
<asp:Label ID="lblMenu" runat="server"></asp:Label>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
</asp:Content>
- B8: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com
for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.UI;
namespace ResponsiveNavigationMenuUsingBootstrap
{
public partial class _Default :
System.Web.UI.Page
{
#region
"Private Methods"
private DataTable
BindParent(int ItemID)
{
DataTable objBind = new
DataTable();
objBind = BindData(ItemID);
return objBind;
}
#endregion
#region
"Create Menu"
private void
CreateMenu()
{
DataTable objBind = new
DataTable();
DataTable
objSubBind = new DataTable();
int i = 1;
string sURL = "";
string sMenuName = "";
objBind = BindData(-1);
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
lblMenu.Controls.Add(new LiteralControl("<div
class=\"container\">"));
lblMenu.Controls.Add(new LiteralControl("<div
class=\"navbar navbar-inverse\"
role=\"navigation\">"));
lblMenu.Controls.Add(new LiteralControl("<div
class=\"container-fluid\">"));
lblMenu.Controls.Add(new LiteralControl("<div
class=\"navbar-header\">"));
lblMenu.Controls.Add(new LiteralControl("<button
type=\"button\" class=\"navbar-toggle collapsed\"
data-toggle=\"collapse\"
data-target=\".navbar-collapse\">"));
lblMenu.Controls.Add(new LiteralControl("<span
class=\"sr-only\">Toggle navigation</span>"));
lblMenu.Controls.Add(new LiteralControl("<span
class=\"icon-bar\"></span>"));
lblMenu.Controls.Add(new LiteralControl("<span
class=\"icon-bar\"></span>"));
lblMenu.Controls.Add(new LiteralControl("<span
class=\"icon-bar\"></span>"));
lblMenu.Controls.Add(new LiteralControl("</button>"));
lblMenu.Controls.Add(new LiteralControl("</div>"));
//navbar
lblMenu.Controls.Add(new LiteralControl("<div
class=\"navbar-collapse collapse\" style=\"height:
1px;\">"));
lblMenu.Controls.Add(new LiteralControl("<ul
class=\"nav navbar-nav\">"));
foreach (DataRow
row in objBind.Rows)
{
sMenuName = row["MenuName"].ToString();
sURL = row["URL"].ToString();
if (i == 1)
{
lblMenu.Controls.Add(new LiteralControl("<li
class=\"active\"><a href=" + sURL + "><span class=\"glyphicon
glyphicon-home\"></span> " + sMenuName + "</a></li>"));
}
else
{
//Check Parent
int MenuID;
MenuID = (int)row["MenuID"];
objSubBind =
BindParent(MenuID);
if (objSubBind != null)
{
if (objSubBind.Rows.Count > 0)
{
lblMenu.Controls.Add(new LiteralControl("<li
class=\"dropdown\">"));
lblMenu.Controls.Add(new LiteralControl("<a
href=" + sURL + "
class=\"dropdown-toggle\"
data-toggle=\"dropdown\">" + sMenuName + "<b
class=\"caret\"></b></a>"));
lblMenu.Controls.Add(new LiteralControl("<ul
class=\"dropdown-menu\">"));
foreach (DataRow
subrow in objSubBind.Rows)
{
sMenuName = subrow["MenuName"].ToString();
sURL =
subrow["URL"].ToString();
lblMenu.Controls.Add(new LiteralControl("<li><a href=" + sURL + ">" + sMenuName + "</a></li>"));
}
lblMenu.Controls.Add(new LiteralControl("</ul>"));
lblMenu.Controls.Add(new LiteralControl("</li>"));
}
else
{
lblMenu.Controls.Add(new LiteralControl("<li><a
href=" + sURL + ">"
+ sMenuName + "</a></li>"));
}
}
else
{
lblMenu.Controls.Add(new LiteralControl("<li><a
href=" + sURL + ">"
+ sMenuName + "</a></li>"));
}
}
i = i + 1;
}
lblMenu.Controls.Add(new LiteralControl("</ul>"));
lblMenu.Controls.Add(new LiteralControl("</div><!--/.nav-collapse
-->"));
lblMenu.Controls.Add(new LiteralControl("</div><!--/.container-fluid
-->"));
lblMenu.Controls.Add(new LiteralControl("</div><!--/.navbar
-->"));
lblMenu.Controls.Add(new LiteralControl("</div>
<!-- /container -->"));
}
}
}
#endregion
#region
"Bind Data"
private DataTable
BindData(int ItemID)
{
SqlDataProvider objSQL = new
SqlDataProvider();
DataTable objBind = objSQL.FillTable("Pro_Menu_List", new ObjectPara("@ItemID", ItemID), new ObjectPara("@IsVisible", 1));
return objBind;
}
#endregion
#region
"Event Handles"
protected void
Page_Load(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
CreateMenu();
}
}
catch
{
}
}
#endregion
}
}VB.NET Code
Namespace ResponsiveNavigationMenuUsingBootstrap
Public Class _Default
Inherits System.Web.UI.Page
#Region "Private
Methods"
Private Function
BindParent(ByVal ItemID As Integer) As DataTable
Dim objBind As New DataTable
objBind = BindData(ItemID)
Return objBind
End Function
#End Region
#Region "Create
Accordion"
Private Sub
CreateMenu()
Dim objBind As New DataTable
Dim objSubBind As New DataTable
Dim iCount As Integer = 0
Dim i As Integer = 1
Dim sURL As String = ""
Dim sMenuName As String = ""
objBind = BindData(-1)
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
With lblMenu
.Controls.Add(New LiteralControl("<div
class=""container"">"))
.Controls.Add(New LiteralControl("<div class=""navbar
navbar-inverse"" role=""navigation"">"))
.Controls.Add(New LiteralControl("<div
class=""container-fluid"">"))
.Controls.Add(New LiteralControl("<div
class=""navbar-header"">"))
.Controls.Add(New LiteralControl("<button type=""button""
class=""navbar-toggle collapsed""
data-toggle=""collapse""
data-target="".navbar-collapse"">"))
.Controls.Add(New LiteralControl("<span
class=""sr-only"">Toggle navigation</span>"))
.Controls.Add(New LiteralControl("<span
class=""icon-bar""></span>"))
.Controls.Add(New LiteralControl("<span
class=""icon-bar""></span>"))
.Controls.Add(New LiteralControl("<span
class=""icon-bar""></span>"))
.Controls.Add(New LiteralControl("</button>"))
.Controls.Add(New LiteralControl("</div>"))
'navbar
.Controls.Add(New LiteralControl("<div class=""navbar-collapse
collapse"" style=""height: 1px;"">"))
.Controls.Add(New LiteralControl("<ul class=""nav
navbar-nav"">"))
For Each row As DataRow In objBind.Rows
sMenuName = row("MenuName").ToString
sURL = row("URL").ToString
If i = 1 Then
.Controls.Add(New LiteralControl("<li
class=""active""><a href=" & sURL
& "><span
class=""glyphicon glyphicon-home""></span> "
& sMenuName & "</a></li>"))
Else
'Check Parent
objSubBind =
BindParent(row("MenuID"))
If Not objSubBind Is Nothing Then
If objSubBind.Rows.Count > 0 Then
.Controls.Add(New LiteralControl("<li
class=""dropdown"">"))
.Controls.Add(New LiteralControl("<a
href=" & sURL & "
class=""dropdown-toggle""
data-toggle=""dropdown"">" & sMenuName
& "<b
class=""caret""></b></a>"))
.Controls.Add(New LiteralControl("<ul
class=""dropdown-menu"">"))
For Each subrow As DataRow In objSubBind.Rows
sMenuName = subrow("MenuName").ToString
sURL = subrow("URL").ToString
.Controls.Add(New LiteralControl("<li><a
href=" & sURL & ">"
& sMenuName & "</a></li>"))
Next
.Controls.Add(New LiteralControl("</ul>"))
.Controls.Add(New LiteralControl("</li>"))
Else
.Controls.Add(New LiteralControl("<li><a
href=" & sURL & ">"
& sMenuName & "</a></li>"))
End If
Else
.Controls.Add(New LiteralControl("<li><a
href=" & sURL & ">"
& sMenuName & "</a></li>"))
End If
End If
i = i + 1
Next
.Controls.Add(New LiteralControl("</ul>"))
.Controls.Add(New LiteralControl("</div><!--/.nav-collapse -->"))
.Controls.Add(New LiteralControl("</div><!--/.container-fluid -->"))
.Controls.Add(New LiteralControl("</div><!--/.navbar -->"))
.Controls.Add(New LiteralControl("</div> <!-- /container -->"))
End With
End If
End If
End Sub
#End Region
#Region "Bind Data"
Private Function
BindData(ByVal ItemID As
Integer) As DataTable
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Menu_List", New ObjectPara("@ItemID", ItemID), _
New ObjectPara("@IsVisible", 1))
Return objBind
End Function
#End Region
#Region "Event
Handles"
Protected Sub Page_Load(ByVal
sender As Object,
ByVal e As
System.EventArgs) Handles
Me.Load
Try
If Page.IsPostBack = False Then
CreateMenu()
End If
Catch ex As Exception
End Try
End Sub
#End Region
End Class
End Namespace
Bây giờ chạy Project và mỗi lần thay đổi kích thước màn hình Menu sẽ tự động thay đổi kích thước phù hợp.
Chúc các bạn thành công!
Quang Bình
No Comment to " Tạo Responsive Menu sử dụng Twitter Bootstrap trong Asp.net "