News Ticker

Menu

Sử dụng Bootstrap để tạo Slide lấy dữ liệu từ SQL Server trong Asp.net

(Cách tạo Slide động trong Asp.net) - Bạn đang cần giới thiệu một loạt các sản phẩm mới, hoặc các sản phẩm tiêu biểu trên Website với mong muốn mang lại sự sinh động và ấn tượng với người xem. Sử dụng Slide là một trong những cách tốt nhất để hiển thị số lượng lớn nội dung cũng như hình ảnh trong một không gian nhỏ trên Website. Hiện có rất nhiều các Plugin hay Jquery hỗ trợ công việc này, tuy nhiên hôm nay Thủ thuật lập trình sẽ giới thiệu với các bạn cách sử dụng Bootstrap để tạo các Slide và các Slide 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 Carousels 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
2Titlenvarchar(150)
3DescriptionntextMô tả
4URLnvarchar(200)Đường dẫn
5SortOrderIntThứ tự sắp xếp
6IsVisiblebitÂn/Hiện


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


B3: Tạo stored procedure trong SQL Server

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

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

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

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

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

set @strOrder =' Order by SortOrder, Title'

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.

Imports System.Data.SqlClient
Imports System.Data

Namespace BootstrapCarousel

    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 sql As StringAs DataTable
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(sql, _connectionString)
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        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

B5: Mở file Site.Master dưới dạng HTML, nhập thêm các thông tin phía dưới thẻ <head runat="server">

<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <style type="text/css">
        h2{
            margin: 0;    
            color: #666;
            padding-top: 90px;
            font-size: 52px;
            font-family: "trebuchet ms", sans-serif;   
        }
        .item{
            background: #333;   
            text-align: center;
            height: 300px !important;
        }
        .carousel{
            margin-top: 20px;
        }
        .bs-example{
               margin: 20px;
        }
    </style>

-B6: 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;
using System.Web;

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

        #region "Create Carousel"

        private void CreateCarousel()
        {
            DataTable objBind = new DataTable();
            int iCount = 0;
            int i = 0;
            objBind = BindData();

            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    iCount = objBind.Rows.Count;

                    lblCarousels.Controls.Add(new LiteralControl("<div class=\"bs-example\">"));
                    lblCarousels.Controls.Add(new LiteralControl("<div id=\"myCarousel\" class=\"carousel slide\" data-interval=\"3000\" data-ride=\"carousel\">"));
                    lblCarousels.Controls.Add(new LiteralControl("<!-- Carousel indicators -->"));

                    lblCarousels.Controls.Add(new LiteralControl("<ol class=\"carousel-indicators\">"));
                    for (i = 0; i <= iCount; i++)
                    {
                        //Active
                        if (i == 0)
                        {
                            lblCarousels.Controls.Add(new LiteralControl("<li data-target=\"#myCarousel\" data-slide-to=" + i + " class=\"active\"></li>"));
                        }
                        else
                        {
                            lblCarousels.Controls.Add(new LiteralControl("<li data-target=\"#myCarousel\" data-slide-to=" + i + "></li>"));
                        }
                    }
                    lblCarousels.Controls.Add(new LiteralControl("</ol>"));

                    lblCarousels.Controls.Add(new LiteralControl("<!-- Carousel items -->"));
                    lblCarousels.Controls.Add(new LiteralControl("<div class=\"carousel-inner\">"));

                    i = 0;
                    foreach (DataRow row in objBind.Rows)
                    {
                        //Active
                        if (i == 0)
                        {
                            lblCarousels.Controls.Add(new LiteralControl("<div class=\"active item\">"));
                        }
                        else
                        {
                            lblCarousels.Controls.Add(new LiteralControl("<div class=\"item\">"));
                        }
                        //==============Title===============
                        lblCarousels.Controls.Add(new LiteralControl("<h2>"));
                        lblCarousels.Controls.Add(new LiteralControl(row["Title"].ToString()));
                        lblCarousels.Controls.Add(new LiteralControl("</h2>"));

                        //==========Description=============
                        lblCarousels.Controls.Add(new LiteralControl("<div class=\"carousel-caption\">"));
                        lblCarousels.Controls.Add(new LiteralControl(row["Description"].ToString()));
                        lblCarousels.Controls.Add(new LiteralControl("</div>"));

                        lblCarousels.Controls.Add(new LiteralControl("</div>"));
                        i = i + 1;
                    }
                    lblCarousels.Controls.Add(new LiteralControl("</div>"));

                    //Carousel nav
                    lblCarousels.Controls.Add(new LiteralControl("<!-- Carousel nav -->"));
                    //Left
                    lblCarousels.Controls.Add(new LiteralControl("<a class=\"carousel-control left\" href=\"#myCarousel\" data-slide=\"prev\">"));
                    lblCarousels.Controls.Add(new LiteralControl("<span class=\"glyphicon glyphicon-chevron-left\"></span>"));
                    lblCarousels.Controls.Add(new LiteralControl("</a>"));
                    //Right
                    lblCarousels.Controls.Add(new LiteralControl("<a class=\"carousel-control right\" href=\"#myCarousel\" data-slide=\"next\">"));
                    lblCarousels.Controls.Add(new LiteralControl("<span class=\"glyphicon glyphicon-chevron-right\"></span>"));
                    lblCarousels.Controls.Add(new LiteralControl("</a>"));

                    lblCarousels.Controls.Add(new LiteralControl("</div>"));
                    lblCarousels.Controls.Add(new LiteralControl("</div>"));
                }
            }
        }

        private DataTable BindData()
        {
            SqlDataProvider objSQL = new SqlDataProvider();

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

        #endregion

        #region "Event Handles"

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

VB.NET Code
Namespace BootstrapCarousel

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Create Carousel"

        Private Sub CreateCarousel()
            Dim objBind As New DataTable
            Dim iCount As Integer = 0
            Dim i As Integer = 0
            objBind = BindData()

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    iCount = objBind.Rows.Count

                    lblCarousels.Controls.Add(New LiteralControl("<div class=""bs-example"">"))
                    lblCarousels.Controls.Add(New LiteralControl("<div id=""myCarousel"" class=""carousel slide"" data-interval=""3000"" data-ride=""carousel"">"))
                    lblCarousels.Controls.Add(New LiteralControl("<!-- Carousel indicators -->"))

                    lblCarousels.Controls.Add(New LiteralControl("<ol class=""carousel-indicators"">"))
                    For i = 0 To iCount
                        'Active
                        If i = 0 Then
                            lblCarousels.Controls.Add(New LiteralControl("<li data-target=""#myCarousel"" data-slide-to=" & i & " class=""active""></li>"))
                        Else
                            lblCarousels.Controls.Add(New LiteralControl("<li data-target=""#myCarousel"" data-slide-to=" & i & "></li>"))
                        End If
                    Next
                    lblCarousels.Controls.Add(New LiteralControl("</ol>"))

                    lblCarousels.Controls.Add(New LiteralControl("<!-- Carousel items -->"))
                    lblCarousels.Controls.Add(New LiteralControl("<div class=""carousel-inner"">"))

                    i = 0
                    For Each row As DataRow In objBind.Rows
                        'Active
                        If i = 0 Then
                            lblCarousels.Controls.Add(New LiteralControl("<div class=""active item"">"))
                        Else
                            lblCarousels.Controls.Add(New LiteralControl("<div class=""item"">"))
                        End If
                        '==============Title===============
                        lblCarousels.Controls.Add(New LiteralControl("<h2>"))
                        lblCarousels.Controls.Add(New LiteralControl(row("Title").ToString))
                        lblCarousels.Controls.Add(New LiteralControl("</h2>"))

                        '==========Description=============
                        lblCarousels.Controls.Add(New LiteralControl("<div class=""carousel-caption"">"))
                        lblCarousels.Controls.Add(New LiteralControl(Server.HtmlDecode(row("Description"))))
                        lblCarousels.Controls.Add(New LiteralControl("</div>"))

                        lblCarousels.Controls.Add(New LiteralControl("</div>"))
                        i = i + 1
                    Next
                    lblCarousels.Controls.Add(New LiteralControl("</div>"))

                    'Carousel nav
                    lblCarousels.Controls.Add(New LiteralControl("<!-- Carousel nav -->"))
                    'Left
                    lblCarousels.Controls.Add(New LiteralControl("<a class=""carousel-control left"" href=""#myCarousel"" data-slide=""prev"">"))
                    lblCarousels.Controls.Add(New LiteralControl("<span class=""glyphicon glyphicon-chevron-left""></span>"))
                    lblCarousels.Controls.Add(New LiteralControl("</a>"))
                    'Right
                    lblCarousels.Controls.Add(New LiteralControl("<a class=""carousel-control right"" href=""#myCarousel"" data-slide=""next"">"))
                    lblCarousels.Controls.Add(New LiteralControl("<span class=""glyphicon glyphicon-chevron-right""></span>"))
                    lblCarousels.Controls.Add(New LiteralControl("</a>"))

                    lblCarousels.Controls.Add(New LiteralControl("</div>"))
                    lblCarousels.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 = objSQL.FillTable("Pro_Carousels_List", New ObjectPara("@IsVisible", 1))
            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
                    CreateCarousel()
                End If
            Catch ex As Exception

            End Try
        End Sub

#End Region
      
    End Class

End Namespace

Chạy Project, các bạn sẽ có một danh sách các slide được lấy từ CSDL SQL Server, với các thông tin được lấy từ CSDL, người sử dụng có thể dễ dàng bổ xung hoặc chỉnh sửa thông tin cho các Slide nhanh chóng và dễ dàng hơn.

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 Bootstrap để tạo Slide lấy dữ liệu từ SQL Server 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