News Ticker

Menu

Sử dụng Repeater để tạo Superfish Menu trong Asp.net

(jQuery Superfish Menu in Asp.net) – Đối với các Website thương mại điện tử, do số lượng các ngành hàng nhiều và có nhiều cấp nên việc phân loại ngành hàng càng đơn giản, thuận tiện càng dễ cho người mua hàng thì hàng hóa sẽ bán được nhiều hơn. 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 Vertical Menu. Menu gồm 3 cấp, các thông tin được lấy từ CSDL SQL Server.

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 jQuerySuperfishMenu
{
    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 jQuerySuperfishMenu

    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 Superfish Menu tại đây

- B7: Copy lần lượt các file superfish.css vào thư mục Style, file jquery.js, hoverIntent.js, superfish.js 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 id="Head1" runat="server">
    <title>jQuery Superfish Menu in Asp.net</title>
    <link href="Styles/Site.css" rel="stylesheet" type="text/css" />
    <link href="Styles/superfish.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="Js/jquery.js"></script>
    <script type="text/javascript" src="Js/hoverIntent.js"></script>
    <script type="text/javascript" src="Js/superfish.js"></script>
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

B9: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ Page Title="jQuery Superfish Menu in Asp.net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jQuerySuperfishMenu._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h3>
        jQuery Superfish Menu in Asp.net
    </h3><br />
    <script type="text/javascript">
        (function ($) {
            $(document).ready(function () {
                var example = $('#example').superfish({
            });
        });
        })(jQuery);
    </script>
    <ul class="sf-menu" id="example">
        <asp:Repeater ID="rptMenu" OnItemDataBound="rptMenu_ItemDataBound" runat="server">
            <ItemTemplate>
                <li>
                    <a href='<%# Eval("URL")%>'><%# Eval("MenuName")%></a>
                    <ul id="level1" runat="server">
                        <asp:Repeater ID="rptMenu1" OnItemDataBound="Detail_Bound" runat="server">
                            <ItemTemplate>
                                <li>
                                    <a href='<%# Eval("URL")%>'><%# Eval("MenuName")%></a>
                                    <ul id="level2" runat="server">
                                        <asp:Repeater ID="rptMenu2" runat="server">
                                            <ItemTemplate>
                                                <li><a href="#"><%# Eval("MenuName")%></a></li>
                                            </ItemTemplate>
                                        </asp:Repeater>
                                    </ul>
                                </li>
                            </ItemTemplate>
                        </asp:Repeater>
                    </ul>
                </li>
            </ItemTemplate>
        </asp:Repeater>
     </ul>
</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.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

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

        private void CreateMenu()
        {
            DataTable objBind = new DataTable();
            objBind = BindData(-1);

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

        #endregion

        #region "Bind Data"

        private DataTable BindData(int ParentID)
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            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 void rptMenu_ItemDataBound(object sender, System.Web.UI.WebControls.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("rptMenu1");
                HtmlGenericControl level1 = (HtmlGenericControl)e.Item.FindControl("level1");

                if (rptMenu != null & level1 != null)
                {
                    if (objBind.Rows.Count > 0)
                    {
                        rptMenu.DataSource = objBind;
                        rptMenu.DataBind();
                        level1.Visible = true;
                    }
                    else
                    {
                        level1.Visible = false;
                    }
                }
                else
                {
                    level1.Visible = false;
                }
            }
        }

        protected void Detail_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");
                HtmlGenericControl level2 = (HtmlGenericControl)e.Item.FindControl("level2");

                if (rptMenu != null & level2 != null)
                {
                    if (objBind.Rows.Count > 0)
                    {
                        rptMenu.DataSource = objBind;
                        rptMenu.DataBind();
                        level2.Visible = true;
                    }
                    else
                    {
                        level2.Visible = false;
                    }
                }
                else
                {
                    level2.Visible = false;
                }
            }
        }

        #endregion

        protected void Page_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 jQuerySuperfishMenu

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Create Menu"

        Private Sub CreateMenu()
            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 Function BindData(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 Sub rptMenu_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptMenu.ItemDataBound
            If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
                Dim MenuID As Integer = DataBinder.Eval(e.Item.DataItem, "MenuID")
                Dim MenuName As String = DataBinder.Eval(e.Item.DataItem, "MenuName")

                Dim objBind As New DataTable
                objBind = BindData(MenuID)
                Dim rptMenu1 As Repeater = DirectCast(e.Item.FindControl("rptMenu1"), Repeater)
                Dim level1 As HtmlControls.HtmlGenericControl = DirectCast(e.Item.FindControl("level1"), HtmlGenericControl)

                If Not rptMenu1 Is Nothing And Not level1 Is Nothing Then
                    If objBind.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 Sub Detail_Bound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
            Try
                If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
                    Dim MenuID As Integer = DataBinder.Eval(e.Item.DataItem, "MenuID")
                    Dim MenuName As String = DataBinder.Eval(e.Item.DataItem, "MenuName")

                    Dim objBind As New DataTable
                    objBind = BindData(MenuID)
                    Dim rptMenu As Repeater = DirectCast(e.Item.FindControl("rptMenu2"), Repeater)
                    Dim level2 As HtmlControls.HtmlGenericControl = DirectCast(e.Item.FindControl("level2"), HtmlGenericControl)

                    If Not rptMenu Is Nothing And 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 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 bạn sẽ có kết quả như ảnh phía dưới.

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

Share This:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Sử dụng Repeater để tạo Superfish Menu trong Asp.net "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM