(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.

Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



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.

STTTên trườngKiểu trườngGhi chú
1MenuIDIntTrường tự tăng
2ParentIDInt
3MenuNamenvarchar(150)Tên Menu
4Descriptionnvarchar(250)Mô tả
5URLnvarchar(200)Đường dẫn Menu
6MenuOrderIntThứ tự sắp xếp
7IsVisiblebitÂ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

Bạn có thể tải về bảng cơ sở dữ liệu SQL bằng cách nhấn vào liên kết tải về dưới đây

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 AsString

#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() AsString
            Get
                Return _connectionString
            End Get
        End Property

#End Region

#Region "Functions"

        Public FunctionFillTable(ByVal sql AsString) As DataTable
            Try
                Dim tb AsNew DataTable
                Dim adap AsNew SqlDataAdapter(sql, _connectionString)
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public FunctionFillTable(ByVal ProcName As String, ByVal ParamArrayPara() As ObjectPara) As DataTable
            Try
                Dim tb AsNew DataTable
                Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                If NotPara Is NothingThen
                    ForEach 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 PropertyName() As String
            Get
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value
            End Set
        End Property

        Public PropertyValue() As Object
            Get
                Return _Value
            End Get
            Set(ByVal value As Object)
                _Value = value
            End Set
        End Property

    End Class

End Namespace

Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config

- 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 {
            width100%;
        }
        .container {
            padding-right2px;
            padding-left2px;
            margin-rightauto;
            margin-leftauto;
        }
    </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 DataTableBindParent(int ItemID)
        {
            DataTable objBind = newDataTable();

            objBind = BindData(ItemID);

            return objBind;
        }

        #endregion

        #region"Create Menu"

        private voidCreateMenu()
        {
            DataTable objBind = newDataTable();
            DataTableobjSubBind = 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 (DataRowrow 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 (DataRowsubrow 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 DataTableBindData(int ItemID)
        {
            SqlDataProvider objSQL = newSqlDataProvider();
            DataTable objBind = objSQL.FillTable("Pro_Menu_List", new ObjectPara("@ItemID", ItemID), new ObjectPara("@IsVisible", 1));
            return objBind;
        }

        #endregion

        #region"Event Handles"

        protected voidPage_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 FunctionBindParent(ByVal ItemID As Integer) As DataTable
            Dim objBind As New DataTable

            objBind = BindData(ItemID)

            Return objBind
        End Function

#End Region

#Region "Create Accordion"

        Private SubCreateMenu()
            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 FunctionBindData(ByVal ItemID AsInteger) 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(ByValsender As Object, ByVal e AsSystem.EventArgs) HandlesMe.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.


Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



Chúc các bạn thành công!

Quang Bình

0 comments Blogger 0 Facebook

Post a Comment

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top