(Cách tạo jQuery Tabs động trong Asp.net) - Trong bài viết “Tạo Tab động sử dụng Ajaxcontroltoolkit trong Asp.net” thủ thuật lập trình đã giới thiệu với các bạn các lợi ích khi sử dụng Tabs trên phần mềm hoặc Website. Hôm nay thủ thuật lập trình sẽ giới thiệu với các bạn thêm 1 cách nữa để có thể tạo Tabs động, đó là sử dụng thư viện jQuery. Nội dung các Tabs được hiển thị từ các Control ngoài và đường dẫn cũng như tên các Control này đượ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 Bảng DynamicTabs có cấu trúc phía dưới trong CSDL SQL Server.

STTTên trườngKiểu trườngGhi chú
1ItemIDIntTrường tự tăng
2TabNamenvarchar(150)
3Descriptionnvarchar(250)Mô tả
4ControlURLnvarchar(250)
5ImageURLnvarchar(250)
6SortOrderIntThứ tự sắp xếp
7IsVisiblebitÂn/Hiện Tab


B2: Nhập dữ liệu cho bảng DynamicTabs


B3: Tạo stored procedure trong SQL Server

CREATE      procedure [dbo].[Pro_DynamicTabs_List]
      @IsVisible bit
as

declare @strSQL   nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)

set @strSQL= 'Select * from DynamicTabs'
set @strWhere =' where 1=1'


if @IsVisible=1
      set @strWhere= @strWhere  +' and (IsVisible=1)'

if @IsVisible=0
      set @strWhere= @strWhere  +' and (IsVisible=0 Or IsVisible Is Null)'

set @strOrder =' Order by SortOrder, TabName'

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
B4: 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.

Namespace DynamicTabsUsingjQuery

    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
                    For Eachp As ObjectParaIn 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

- B5: Tạo thư mục Js trong Project, Download  file jquery.js và copy file vào thư mục vừa tạo

- B6: Tạo file Tabs.css trong thư mục Styles và viết Code cho file

.container
{
    width: 99%; margin: 10px auto;
}

ul.tabs {
       margin: 0;
       padding: 0;
       float: left;
       list-style: none;
       height: 32px;
       border-bottom: 1px solid #999;
       border-left: 1px solid #999;
       width: 100%;
}

ul.tabs li {
       float: left;
       margin: 0;
       padding: 0;
       height: 31px;
       line-height: 31px;
       border: 1px solid #999;
       border-left: none;
       margin-bottom: -1px;
       background: #e0e0e0;
       overflow: hidden;
       position: relative;
       font-family: Arial, Helvetica, sans-serif;
       font-size:12px;
}

ul.tabs li a {
       text-decoration: none;
       color: #000;
       display: block;
       padding: 0 20px;
       border: 1px solid #fff;
       outline: none;
       font-family: Arial, Helvetica, sans-serif;
       font-size:12px;
}

ul.tabs li a:hover {
       background: #ccc;
}     

html ul.tabs li.active, html ul.tabs li.activea:hover  {
       background: #fff;
       border-bottom: 1px solid #fff;
}

.tab_container {
       border: 1px solid #999;
       border-top: none;
       clear: both;
       float: left;
       width: 100%;
       background: #fff;
       -moz-border-radius-bottomright: 5px;
       -khtml-border-radius-bottomright: 5px;
       -webkit-border-bottom-right-radius: 5px;
       -moz-border-radius-bottomleft: 5px;
       -khtml-border-radius-bottomleft: 5px;
       -webkit-border-bottom-left-radius: 5px;
}

.tab_content {
       padding: 20px;
       font-size: 1.2em;
}

.tab_content h2{
       font-weight: normal;
       padding-bottom: 10px;
       border-bottom: 1px dashed #ddd;
       font-size: 1.8em;
}

.tab_content h3a{
       color: #254588;

}


- B7: Gắn file Tabs.css vào file Site.Master

<link href="~/Styles/Site.css" rel="stylesheet"type="text/css"/>

<link href="~/Styles/Tabs.css" rel="stylesheet"type="text/css"/>


B8: Mở file Default.aspxdưới dạng HTML và nhập mã HTML

<%@ PageTitle="Dynamic Tabs Using jQuery in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="DynamicTabsUsingjQuery._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1"runat="server">
    </asp:ScriptManager>
    <h1>
        Dynamic Tabs Using jQuery in ASP.Net
    </h1>
    <br />
    <script type="text/javascript"src="Js/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            //Default Action
            $(".tab_content").hide(); //Hide all content
            $("ul.tabs li:first").addClass("active").show(); //Activate first tab
            $(".tab_content:first").show(); //Show first tab content

            //On Click Event
            $("ul.tabs li").click(function () {
                $("ul.tabs li").removeClass("active"); //Remove any "active" class
                $(this).addClass("active"); //Add "active" class to selected tab
                $(".tab_content").hide(); //Hide all tab content
                var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
                $(activeTab).fadeIn(); //Fade in the active content
                return false;
            });
        });
    </script>
    <asp:Panel ID="pnlTabs"CssClass="container"runat="server">
    </asp:Panel>
</asp:Content>

B9: 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.Diagnostics;
using System.Web.UI;

namespace DynamicTabsUsingjQuery
{
    public partial class _Default : System.Web.UI.Page
    {

        #region"Create Tabs"

        private voidCreateTabs()
        {
            DataTable objBind = newDataTable();

            Control myCtrl = newControl();
            int i = 1;
            int j = 1;
            string TabName = "";
            string ControlURL = "";

            objBind = BindData();

            pnlTabs.Controls.Clear();
            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    pnlTabs.Controls.Add(new LiteralControl("<ul class=\"tabs\">"));
                    foreach(DataRow row inobjBind.Rows)
                    {
                        if (row != null)
                        {
                            TabName = row["TabName"].ToString();
                            pnlTabs.Controls.Add(new LiteralControl("<li><a href=\"#tab" + j + "\">"+ TabName + "</a></li>"));
                        }
                        j = j + 1;
                    }
                    pnlTabs.Controls.Add(new LiteralControl("</ul>"));

                    pnlTabs.Controls.Add(new LiteralControl("<div class=\"tab_container\">"));
                    foreach (DataRowrow in objBind.Rows)
                    {
                        if (row != null)
                        {
                            ControlURL = row["ControlURL"].ToString();
                            if (File.Exists(Server.MapPath("~/" + ControlURL)))
                            {
                                myCtrl = Page.LoadControl(ControlURL);
                            }
                            pnlTabs.Controls.Add(new LiteralControl("<div id=\"tab" + i + "\" class=\"tab_content\">"));
                            pnlTabs.Controls.Add(myCtrl);
                            pnlTabs.Controls.Add(new LiteralControl("</div>"));
                        }
                        i = i + 1;
                    }
                    pnlTabs.Controls.Add(new LiteralControl("</div>"));
                }
            }
        }

        private DataTableBindData()
        {
            SqlDataProvider objSQL = newSqlDataProvider();

            DataTable objBind = objSQL.FillTable("Pro_DynamicTabs_List", new ObjectPara("@IsVisible", 1));
            return objBind;
        }

        #endregion

        #region"Event Handles"

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

        #endregion
    }
}

VB.NET Code
Imports System.IO

Namespace DynamicTabsUsingjQuery

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Tabs"

        Private SubCreateTabs()
            Dim objBind As New DataTable
            Dim tabIndex As Integer = 1

            If Not Session("ActiveTabIndex") Is Nothing Then
                tabIndex = Session("ActiveTabIndex")
            End If

            Dim myCtrl As New Control
            Dim i As Integer = 1
            Dim j As Integer = 1
            Dim TabName As String = ""
            Dim ControlURL As String = ""

            objBind = BindData()

            pnlTabs.Controls.Clear()
            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    pnlTabs.Controls.Add(New LiteralControl("<ul class=""tabs"">"))
                    For Eachrow As DataRowIn objBind.Rows
                        If Not row Is Nothing Then
                            TabName = row("TabName").ToString()
                            pnlTabs.Controls.Add(New LiteralControl("<li><a href=""#tab" & j & """>"& TabName & "</a></li>"))
                        End If
                        j = j + 1
                    Next
                    pnlTabs.Controls.Add(New LiteralControl("</ul>"))

                    pnlTabs.Controls.Add(New LiteralControl("<div class=""tab_container"">"))
                    For Eachrow As DataRowIn objBind.Rows
                        If Not row Is Nothing Then
                            ControlURL = row("ControlURL").ToString()
                            If File.Exists(Server.MapPath("~/" & ControlURL)) Then
                                myCtrl = Page.LoadControl(ControlURL)
                            End If
                            pnlTabs.Controls.Add(New LiteralControl("<div id=""tab" & i & """ class=""tab_content"">"))
                            pnlTabs.Controls.Add(myCtrl)
                            pnlTabs.Controls.Add(New LiteralControl("</div>"))
                        End If
                        i = i + 1
                    Next
                    pnlTabs.Controls.Add(New LiteralControl("</div>"))
                End If
            End If
        End Sub

#End Region

#Region "Bind Data"

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

#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
                    CreateTabs()
                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