News Ticker

Menu

Tạo Pill Tabs động sử dụng bootstrap trong Asp.net

(Dynamic Bootstrap Pill Tabs) – Trong các bài viết trước, thủ thuật lập trình đã giới thiệu với các bạn nhiều cách để tạo Tabs động sử dụng jQuery, AjaxControlToolkit. Hôm nay thủ thuật lập trình sẽ giới thiệu với các bạn cách để tạo tạo Tab sử dụng thư viện bootstrap. 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.

Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube



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



B1: Tạo CSDL SQL DynamicTabs

B2: 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


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


B4: 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
- 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 DynamicBootstrapPillTabs
{
    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 DynamicBootstrapPillTabs

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

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

B6: Mở file Site.Master dạng HTML và bổ xung đoạn mã phía dưới trong thẻ Head
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" />
    <link rel="stylesheet" href="Styles/bootstrap.vertical-tabs.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="http://netdna.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>

- B7: Tạo thư mục Controls, lần lượt tạo các file Tab1.ascx, Tab2.ascx, Tab3.ascx, Tab4.ascx, Tab5.ascx trong thư mục này. Mỗi file sẽ nhập nội dung để phân biệt giữa các Control với nhau.

B8: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C#
<%@ Page Title=" Bootstrap Pill Tabs in ASP.Net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DynamicBootstrapPillTabs._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>
    <h3>
        Bootstrap Pill Tabs in ASP.Net
    </h3>
    <asp:Panel ID="pnlTabs" runat="server">
    </asp:Panel>
</asp:Content>

VB.Net Code
<%@ Page Title="Dynamic Bootstrap Pill Tabs in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="DynamicBootstrapPillTabs._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>
    <h3>
        Bootstrap Pill Tabs in ASP.Net
    </h3>
    <asp:Panel ID="pnlTabs" runat="server">
    </asp:Panel>
</asp:Content>

B9: Viết Code cho file Default.aspx

C#
//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 DynamicBootstrapPillTabs
{
    public partial class _Default : System.Web.UI.Page
    {

        #region "Create Tabs"

        private void CreateTabs()
              {
                     DataTable objBind = new DataTable();
                     Control myCtrl = new Control();
                     int i = 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=\"nav nav-pills\">"));
                                  foreach (DataRow row in objBind.Rows) {
                                         if ((row != null)) {
                                                TabName = row["TabName"].ToString();
                                                if (i == 1) {
                                                       pnlTabs.Controls.Add(new LiteralControl("<li class=\"active\"><a href=\"#tab" + i + "\" data-toggle=\"tab\">" + TabName + "</a></li>"));
                                                } else {
                                                       pnlTabs.Controls.Add(new LiteralControl("<li><a href=\"#tab" + i + "\" data-toggle=\"tab\">" + TabName + "</a></li>"));
                                                }
                                         }
                                         i = i + 1;
                                  }
                                  pnlTabs.Controls.Add(new LiteralControl("</ul>"));

                                  i = 1;
                    pnlTabs.Controls.Add(new LiteralControl("<div class=\"tab-content\">"));
                                  pnlTabs.Controls.Add(new LiteralControl("<!-- Tab panes -->"));
                                  foreach (DataRow row in objBind.Rows) {
                                         if (row != null) {
                                                ControlURL = row["ControlURL"].ToString();
                                                if (File.Exists(Server.MapPath("~/" + ControlURL))) {
                                                       myCtrl = Page.LoadControl(ControlURL);
                                                }
                                                if (i == 1) {
                                pnlTabs.Controls.Add(new LiteralControl("<div class=\"tab-pane fade in active\" id=\"tab" + i + "\">"));
                                                } else {
                                pnlTabs.Controls.Add(new LiteralControl("<div class=\"tab-pane fade\" id=\"tab" + i + "\">"));
                                                }
                                                pnlTabs.Controls.Add(myCtrl);
                                                pnlTabs.Controls.Add(new LiteralControl("</div>"));
                                         }
                                         i = i + 1;
                                  }
                    pnlTabs.Controls.Add(new LiteralControl("</div>"));
                           }
                     }
              }

        private DataTable BindData()
              {
                     SqlDataProvider objSQL = new SqlDataProvider();
                     DataTable objBind = null;
                     //Caching
            if (Cache["Cache_PillTabs"] == null)
            {
                           objBind = objSQL.FillTable("Pro_DynamicTabs_List", new ObjectPara("@IsVisible", 1));
                Cache["Cache_PillTabs"] = objBind;
                     } else {
                objBind = (DataTable)Cache["Cache_PillTabs"];
                     }
                     return objBind;
              }

              #endregion

        #region "Event Handles"

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

        #endregion
    }
}

VB.NET Code

'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.IO

Namespace DynamicBootstrapPillTabs

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Tabs"

        Private Sub CreateTabs()
            Dim objBind As New DataTable
            Dim myCtrl As New Control
            Dim i 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=""nav nav-pills"">"))
                    For Each row As DataRow In objBind.Rows
                        If Not row Is Nothing Then
                            TabName = row("TabName").ToString()
                            If i = 1 Then
                                pnlTabs.Controls.Add(New LiteralControl("<li class=""active""><a href=""#tab" & i & """ data-toggle=""tab"">" & TabName & "</a></li>"))
                            Else
                                pnlTabs.Controls.Add(New LiteralControl("<li><a href=""#tab" & i & """ data-toggle=""tab"">" & TabName & "</a></li>"))
                            End If
                        End If
                        i = i + 1
                    Next
                    pnlTabs.Controls.Add(New LiteralControl("</ul>"))

                    i = 1
                    pnlTabs.Controls.Add(New LiteralControl("<div class=""tab-content"">"))
                    pnlTabs.Controls.Add(New LiteralControl("<!-- Tab panes -->"))
                    For Each row As DataRow In 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
                            If i = 1 Then
                                pnlTabs.Controls.Add(New LiteralControl("<div class=""tab-pane fade in active"" id=""tab" & i & """>"))
                            Else
                                pnlTabs.Controls.Add(New LiteralControl("<div class=""tab-pane fade"" id=""tab" & i & """>"))
                            End If
                            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 Function BindData() As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable
            'Caching
            If Cache("Cache_PillTabs") Is Nothing Then
                objBind = objSQL.FillTable("Pro_DynamicTabs_List", New ObjectPara("@IsVisible", 1))
                Cache("Cache_PillTabs") = objBind
            Else
                objBind = CType(Cache("Cache_PillTabs"), DataTable)
            End If
            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
                    CreateTabs()
                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 " Tạo Pill Tabs động sử dụng bootstrap 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