(Dynamic jQuery Mega DropDown Menu in Asp.net) – Mega Menu đã quá quen thuộc với những người lập trình Web, nó giúp người lập trình  có thể hiển thị dễ dàng với những loại danh mục có nhiều cấp và số lượng lớn. Với jQuery Mega Drop Down Menu ta thường quen với dạng HTML, vậy có thể tạo nó hoàn toàn động không? Bài viết dưới đây sẽ hướng dẫn các bạn cách sử dụng Control Repeater và thư viện jQuery  để tạo Mega DropDown Menu. Menu gồm 3 cấp, các thông tin được lấy từ CSDL SQL Server.


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 DynamicallyMenu trong SQL Server

B2: Tạo Bảng MenuItems có cấu trúc phía dưới trong CSDL SQL Server.
B3: Nhập dữ liệu cho bảng MenuItems

B4: Tạo stored procedure trong SQL Server
CREATE    Procedure [dbo].[Pro_Menu_List]
      @ParentID int,
      @IsVisible bit
as
declare @strSQL   nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)

set @strSQL= 'Select * from MenuItems'
set @strWhere =' where 1=1'
if @IsVisible=0
      set @strWhere= @strWhere  +' and (IsVisible=0 Or IsVisible Is Null)'

if @ParentID<>-And @ParentID<>0
      set @strWhere= @strWhere  +' and ParentID='+ convert(nvarchar,@ParentID)

if @ParentID=-1
      set @strWhere= @strWhere  +' and (ParentID=-1 Or ParentID 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.
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace namespace jQueryMegaDropDownMenu
{
    public class SqlDataProvider
    {
        #region "Membres Prives"

        private string _connectionString;

        #endregion

        #region "Constructeurs"

        public SqlDataProvider()
        {
            try
            {
                _connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
            }
            catch
            {
            }
        }

        #endregion

        #region "Proprietes"

        public string ConnectionString
        {
            get { return _connectionString; }
        }

        #endregion

        #region "Functions"

        public DataTable FillTable(string ProcName, params ObjectPara[] Para)
        {
            try
            {
                DataTable tb = new DataTable();
                SqlDataAdapter adap = new SqlDataAdapter(ProcName, _connectionString);
                adap.SelectCommand.CommandType = CommandType.StoredProcedure;
                if (Para != null)
                {
                    foreach (ObjectPara p in Para)
                    {
                        adap.SelectCommand.Parameters.Add(new SqlParameter(p.Name, p.Value));
                    }
                }
                adap.Fill(tb);
                return tb;
            }
            catch
            {
                return null;
            }
        }
        #endregion
    }

    public class ObjectPara
    {
        string _name;

        object _Value;
        public ObjectPara(string Pname, object PValue)
        {
            _name = Pname;
            _Value = PValue;
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public object Value
        {
            get { return _Value; }
            set { _Value = value; }
        }
    }
}
VB.NET Code
Imports System.Data.SqlClient
Imports System.Data

Namespace namespace jQueryMegaDropDownMenu

    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 ProcName As StringByVal ParamArray Para() As ObjectParaAs 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 StringByVal 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

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

- B6: Download thư viện dcmegamenu tại đây

- B7: Giải nén -> Copy lần lượt các file menu.css vào thư mục Style, file jquery.dcmegamenu.1.2.js, jquery.hoverIntent.minified vào thư mục Js

B8: Mở file Site.Master dạng HTML và bổ xung đoạn mã phía dưới trong thẻ Head
<head runat="server">
    <title>Dynamic jQuery Mega DropDown Menu in Asp.net</title>
    <link href="Styles/Site.css"rel="stylesheet"type="text/css"/>
    <link href="Styles/menu.css"rel="stylesheet"type="text/css"/>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type='text/javascript'src='Js/jquery.hoverIntent.minified.js'></script>
    <script type='text/javascript'src='Js/jquery.dcmegamenu.1.2.js'></script>
    <asp:ContentPlaceHolderID="HeadContent"runat="server">
    </asp:ContentPlaceHolder>
</head>

B9: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ PageTitle="jQuery Mega DropDown Menu in Asp.net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jQueryMegaDropDownMenu._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h3>
        jQuery Mega DropDown Menu in Asp.net
    </h3><br />
    <script type="text/javascript">
        $(document).ready(function ($) {
            $('#mega-menu-tut').dcMegaMenu({
                rowItems: '3',
                speed: 'fast'
            });
        });
    </script>
    <div class="dcjq-mega-menu">
        <ul id="mega-menu-tut"class="menu">
            <asp:Repeater ID="rptMenu"OnItemDataBound="rptMenu_ItemDataBound"runat="server">
                <ItemTemplate>
                    <liid='<%# Eval("Css")%>'>
                        <a href="#"><%# Eval("MenuName")%></a>
                        <ul id="level1" runat="server">
                            <asp:Repeater ID="rptMenu1"OnItemDataBound="Detail_Bound"runat="server">
                                <ItemTemplate>
                                    <li id='<%# Eval("Css")%>'>
                                        <a href="#"><%# Eval("MenuName")%></a>
                                        <ul id="level2" runat="server">
                                            <asp:Repeater ID="rptMenu2"runat="server">
                                                <ItemTemplate>
                                                    <liid='<%# Eval("Css")%>'>
                                                        <a href="#"><%# Eval("MenuName")%></a>
                                                    </li>
                                                </ItemTemplate>
                                            </asp:Repeater>
                                        </ul>
                                    </li>
                                </ItemTemplate>
                            </asp:Repeater>
                        </ul>
                    </li>
                </ItemTemplate>
            </asp:Repeater>
           </ul>
     </div>
</asp:Content>

B10: 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.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace jQueryMegaDropDownMenu
{
    public partial class _Default : System.Web.UI.Page
    {
        #region"Create Menu"

        private voidCreateMenu()
        {
            DataTable objBind = newDataTable();
            objBind = BindData(-1);

            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    rptMenu.DataSource = objBind;
                    rptMenu.DataBind();
                }
            }
        }

        #endregion

        #region"Bind Data"

        private DataTableBindData(int ParentID)
        {
            SqlDataProvider objSQL = newSqlDataProvider();
            DataTable objBind = objSQL.FillTable("Pro_Menu_List", new ObjectPara("@ParentID", ParentID), new ObjectPara("@IsVisible", 1));
            return objBind;
        }

        #endregion

        #region"Event Handles"

        #region"Repeater Methods"

        protected voidrptMenu_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgse)
        {
            if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
            {
                int MenuID = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "MenuID"));
                stringMenuName = DataBinder.Eval(e.Item.DataItem, "MenuName").ToString();

                DataTable objBind = new DataTable();
                objBind = BindData(MenuID);
                Repeater rptMenu = (Repeater)e.Item.FindControl("rptMenu1");
                if (rptMenu != null)
                {
                    rptMenu.DataSource = objBind;
                    rptMenu.DataBind();
                }
            }
        }

        protected voidDetail_Bound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
            {
                int MenuID = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "MenuID"));
                string MenuName = DataBinder.Eval(e.Item.DataItem, "MenuName").ToString();

                DataTable objBind = new DataTable();
                objBind = BindData(MenuID);
                Repeater rptMenu = (Repeater)e.Item.FindControl("rptMenu2");
                if (rptMenu != null)
                {
                    rptMenu.DataSource = objBind;
                    rptMenu.DataBind();
                }
            }
        }

        #endregion

        protected voidPage_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                   CreateMenu();
                }
            }
            catch
            {
            }
        }

        #endregion
    }
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials

Namespace jQueryMegaDropDownMenu

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Create Menu"

        Private SubCreateMenu()
            Dim objBind As New DataTable
            objBind = BindData(-1)

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    rptMenu.DataSource = objBind
                    rptMenu.DataBind()
                End If
            End If
        End Sub

#End Region

#Region "Bind Data"

        Private FunctionBindData(ByVal ParentID As Integer) As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Pro_Menu_List", New ObjectPara("@ParentID", ParentID), New ObjectPara("@IsVisible", 1))
            Return objBind
        End Function

#End Region

#Region "Repeater Methods"

        Private SubrptMenu_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) HandlesrptMenu.ItemDataBound
            If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
                Dim MenuID AsInteger = DataBinder.Eval(e.Item.DataItem, "MenuID")
                Dim MenuName AsString = DataBinder.Eval(e.Item.DataItem, "MenuName")

                Dim objBind AsNew DataTable
                objBind = BindData(MenuID)

                Dim rptMenu1 AsRepeater = DirectCast(e.Item.FindControl("rptMenu1"), Repeater)
                Dim level1 AsHtmlControls.HtmlGenericControl = DirectCast(e.Item.FindControl("level1"), HtmlGenericControl)

                If NotrptMenu1 Is NothingAnd Not level1 Is Nothing Then
                    IfobjBind.Rows.Count > 0 Then
                        rptMenu1.DataSource = objBind
                        rptMenu1.DataBind()
                        level1.Visible = True
                    Else
                        level1.Visible = False
                    End If
                Else
                    level1.Visible = False
                End If
            End If
        End Sub

        Public SubDetail_Bound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
            Try
                If (e.Item.ItemType = ListItemType.Item Ore.Item.ItemType = ListItemType.AlternatingItem) Then
                    Dim MenuID AsInteger = DataBinder.Eval(e.Item.DataItem, "MenuID")
                    Dim MenuName AsString = DataBinder.Eval(e.Item.DataItem, "MenuName")

                    Dim objBind AsNew DataTable
                    objBind = BindData(MenuID)
                    Dim rptMenu AsRepeater = DirectCast(e.Item.FindControl("rptMenu2"), Repeater)
                    Dim level2 AsHtmlControls.HtmlGenericControl = DirectCast(e.Item.FindControl("level2"), HtmlGenericControl)

                    If NotrptMenu Is NothingAnd Not level2 Is Nothing Then
                        If objBind.Rows.Count > 0 Then
                            rptMenu.DataSource = objBind
                            rptMenu.DataBind()
                            level2.Visible = True
                        Else
                            level2.Visible = False
                        End If
                    Else
                        level2.Visible = False
                    End If
                End If
            Catch exception As Exception

            End Try
        End Sub

#End Region

#Region "Event Handles"

        Protected SubPage_Load(ByVal sender AsObject, 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

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