(Dynamic Responsive Moving Box Carousel  in Asp.net) – Những Carousel đẹp sẽ gây ấn tượng đến người xem, nhờ đó những thông tin mới, những sự kiện quan trọng, những sản phẩm mới sẽ được quan tâm và chú ý hơn. Bài viết dưới đây sẽ hướng dẫn các bạn cách sử dụng thư viện Bootstrap kết hợp với Repeater để tạo Carousel dạng Moving Box.


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 Project trong Microsoft Visual Studio 2010

B2: Download thư viện ảnh tại đây và copy vào thư mục Images

B3: Mở file Site.Master dạng HTML và bổ xung đoạn mã phía dưới trong thẻ Head
<head runat="server">
    <title>Responsive Moving Box Carousel in Asp.net Repeater</title>
    <link rel='stylesheet prefetch'href='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.min.css'/>
    <link href="Styles/Site.css"rel="stylesheet"type="text/css"/>
    <script type="text/javascript"src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <script type="text/javascript"src='http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/js/bootstrap.min.js'></script>
    <asp:ContentPlaceHolderID="HeadContent"runat="server">
    </asp:ContentPlaceHolder>
</head>

B4: Mở file Site.css bổ xung đoạn mã phía dưới
/* Global */
body {
    background: #3399cc;
    padding: 40px;

img { max-width:100%; }
a {
       -webkit-transition: all150ms ease;
       -moz-transition: all 150ms ease;
       -ms-transition: all 150ms ease;
       -o-transition: all 150ms ease;
       transition: all 150ms ease;
}
a:hover {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; /* IE 8 */
    filter: alpha(opacity=50); /* IE7 */
    opacity: 0.6;
    text-decoration: none;
}

/* Container */
.container-fluid {
    background: #FFFFFF;
    margin: 40px auto 10px;
    padding: 20px 40px 0;
    max-width: 960px;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
}

/* Page Header */
.page-header {
    background: #f9f9f9;
    margin: -30px -40px 40px;
    padding: 20px 40px;
    border-top: 4px solid #ccc;
    color: #999;
    text-transform: uppercase;
}
.page-header h3{
    line-height: 0.88rem;
    color: #000;
}

/* Thumbnail Box */
.caption h4 {
    font-size: 1rem;
    color: #444;
    }
.caption p {
    font-size: 0.75rem;
    color: #999;
    }
.btn.btn-mini {
    font-size: 0.63rem;
    }

/* Carousel Control */
.control-box {
    text-align: right;
    width: 100%;
    }
.carousel-control{
    background: #666;
    border: 0px;
    border-radius: 0px;
    display: inline-block;
    font-size: 34px;
    font-weight: 200;
    line-height: 18px;
    opacity: 0.5;
    padding: 4px 10px 0px;
    position: static;
    height: 30px;
    width: 15px;
}

/* Footer */
.footer {
    margin: auto;
    width: 100%;
    max-width: 960px;
    display: block;
    font-size: 0.69rem;
    }
   
.footer, .footer a {
    color: #c9e4f7;
    }
   
p.right  {
    float: right;
    }

/* Mobile Only */
@media (max-width: 767px) {
    .page-header, .control-box{
    text-align: center;
    }
}
@media (max-width: 479px) {
    .caption {
    word-break: break-all;
    }
}

B5: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
<%@ PageTitle="Responsive Moving Box Carousel in Repeater Asp.net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ResponsiveMovingBoxCarousel._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <script type="text/javascript">
        $(document).ready(function () {
            $('.carousel').carousel({
                interval: 6000
            })
        });
    </script>
    <div class="container-fluid">
        <div class="row-fluid">
            <div class="span12">
                <divclass="page-header">
                    <h3>Bootstrap</h3>
                    <p>Responsive Moving Box Carousel in Repeater Asp.net</p>
                </div>
                <divclass="carousel slide" id="myCarousel">
                    <divclass="control-box">                           
                        <a data-slide="prev" href="#myCarousel" class="carousel-control left"></a>
                        <a data-slide="next" href="#myCarousel" class="carousel-control right"></a>
                    </div><!-- /.control-box -->  

                    <divclass="carousel-inner">
                        <asp:Repeater ID="rptObject" OnItemDataBound="rptObject_ItemDataBound" runat="server">
                            <ItemTemplate>
                                <asp:Literal ID="ltCarousel"runat="server"></asp:Literal>
                            </ItemTemplate>
                         </asp:Repeater>  
                    </div>             
                </div><!-- /#myCarousel -->
            </div><!-- /.span12 -->         
        </div><!-- /.row -->
    </div><!-- /.container -->
</asp:Content>

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

namespace ResponsiveMovingBoxCarousel
{
    public partial class _Default : System.Web.UI.Page
    {
        #region"Private Members"

        private intItemActive = 1;
        private intItemPerSlide = 4;
        private int Slide = 1;

        #endregion

        #region"Bind Data"

        private voidBindData()
        {
            DataTable objBind = newDataTable();
            objBind.Columns.Add("CarouselName", typeof(string));
            objBind.Columns.Add("ImageName", typeof(string));
            objBind.Columns.Add("URL", typeof(string));
            objBind.Columns.Add("Description", typeof(string));

            objBind.Rows.Add("Dandelion", "Images/dandelion.jpg", "", "Bright little dandelion");
            objBind.Rows.Add("Sakura Trees", "Images/sakura-trees.jpg", "", "A sweet aroma around the trees");
            objBind.Rows.Add("Red Tulips", "Images/tulips.jpg", "", "Beautiful tulips under the sun");
            objBind.Rows.Add("Golden Wheat Field", "Images/golden-wheat-field.jpg", "", "Waving in the sunlight all day");

            objBind.Rows.Add("Autumn", "Images/sunny-day.jpg", "", "Autumn, a season full of great things");
            objBind.Rows.Add("Night In The City", "Images/night-in-the-city.jpg", "", "Silent and beautiful night in the city");
            objBind.Rows.Add("Daffodil Flowers", "Images/daffodil-flowers.jpg", "", "Beside the lake, beneath the trees");
            objBind.Rows.Add("White Wedding Bouquet", "Images/white-wedding-bouquet.jpg", "", "A formal wedding posy of White Tulips");

            objBind.Rows.Add("Sydney", "Images/sydney.jpg", "", "Opera House");
            objBind.Rows.Add("London", "Images/london.jpg", "", "London");
            objBind.Rows.Add("Rio de Janeiro", "Images/rio.jpg", "", "Rio de Janeiro, Brazil");
            objBind.Rows.Add("San Francisco, USA", "Images/san-francisco.jpg", "", "Golden Gate Bridge");

            rptObject.DataSource = objBind;
            rptObject.DataBind();
        }

        #endregion

        #region"Repeater Methods"

        protected voidrptObject_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgse)
        {
            if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
            {
                string CarouselName = DataBinder.Eval(e.Item.DataItem, "CarouselName").ToString();
                string ImageName = DataBinder.Eval(e.Item.DataItem, "ImageName").ToString();
                string URL = DataBinder.Eval(e.Item.DataItem, "URL").ToString();
                string Description = DataBinder.Eval(e.Item.DataItem, "Description").ToString();
                string sCarousel = "";
                LiteralltCarousel = (Literal)e.Item.FindControl("ltCarousel");

                if (ItemActive <= ItemPerSlide)
                {
                    if (ItemActive == 1)
                    {
                        sCarousel += "<div class=\"item active\">";
                        sCarousel += "<ul class=\"thumbnails\">";
                        //Slide += 1
                    }
                    sCarousel += "<li class=\"span3\">";
                    sCarousel += "<div class=\"thumbnail\">";
                    sCarousel += "<img width=\"200px\" height=\"200px\" src=\"" + Page.ResolveUrl(ImageName) + "\" alt=\"\" />";
                    sCarousel += "</div>";
                    sCarousel += "<div class=\"caption\">";
                    sCarousel += "<h4>" + CarouselName + "</h4>";
                    sCarousel += "<p>" + Description + "</p>";
                    sCarousel += "<a class=\"btn btn-mini\" href=" + URL + ">» Read More</a>";
                    sCarousel += "</div>";
                    sCarousel += "</li>";

                    if (ItemActive == ItemPerSlide)
                    {
                        sCarousel += "</ul>";
                        sCarousel += "</div><!-- /Slide1 --> ";
                    }
                }
                else
                {
                    if (ItemActive == (ItemPerSlide * Slide) + 1)
                    {
                        sCarousel += "<div class=\"item\">";
                        sCarousel += "<ul class=\"thumbnails\">";
                        Slide += 1;
                    }
                    sCarousel += "<li class=\"span3\">";
                    sCarousel += "<div class=\"thumbnail\">";
                    sCarousel += "<img width=\"200px\" height=\"200px\" src=\"" + Page.ResolveUrl(ImageName) + "\" alt=\"\" />";
                    sCarousel += "</div>";
                    sCarousel += "<div class=\"caption\">";
                    sCarousel += "<h4>" + CarouselName + "</h4>";
                    sCarousel += "<p>" + Description + "</p>";
                    sCarousel += "<a class=\"btn btn-mini\" href=" + URL + ">» Read More</a>";
                    sCarousel += "</div>";
                    sCarousel += "</li>";
                   
                    if (ItemActive == (ItemPerSlide * Slide))
                    {
                        sCarousel += "</ul>";
                        sCarousel += "</div><!-- /Slide2 --> ";
                    }
                }
                ItemActive += 1;
                ltCarousel.Text = sCarousel;
            }
        }

        #endregion

        #region"Event Handles"

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

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

Namespace ResponsiveMovingBoxCarousel

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Members"

        Private ItemActive AsInteger = 1
        Private ItemPerSlide AsInteger = 4
        Private Slide As Integer = 1

#End Region

#Region "Bind Data"

        Private SubBindData()
            Dim objBind As New DataTable
            With objBind.Columns
                .Add("CarouselName", GetType(String))
                .Add("ImageName", GetType(String))
                .Add("URL", GetType(String))
                .Add("Description", GetType(String))
            End With
          
            objBind.Rows.Add("Dandelion", "Images/dandelion.jpg", "", "Bright little dandelion")
            objBind.Rows.Add("Sakura Trees", "Images/sakura-trees.jpg", "", "A sweet aroma around the trees")
            objBind.Rows.Add("Red Tulips", "Images/tulips.jpg", "", "Beautiful tulips under the sun")
            objBind.Rows.Add("Golden Wheat Field", "Images/golden-wheat-field.jpg", "", "Waving in the sunlight all day")

            objBind.Rows.Add("Autumn", "Images/sunny-day.jpg", "", "Autumn, a season full of great things")
            objBind.Rows.Add("Night In The City", "Images/night-in-the-city.jpg", "", "Silent and beautiful night in the city")
            objBind.Rows.Add("Daffodil Flowers", "Images/daffodil-flowers.jpg", "", "Beside the lake, beneath the trees")
            objBind.Rows.Add("White Wedding Bouquet", "Images/white-wedding-bouquet.jpg", "", "A formal wedding posy of White Tulips")

            objBind.Rows.Add("Sydney", "Images/sydney.jpg", "", "Opera House")
            objBind.Rows.Add("London", "Images/london.jpg", "", "London")
            objBind.Rows.Add("Rio de Janeiro", "Images/rio.jpg", "", "Rio de Janeiro, Brazil")
            objBind.Rows.Add("San Francisco, USA", "Images/san-francisco.jpg", "", "Golden Gate Bridge")

            rptObject.DataSource = objBind
            rptObject.DataBind()
        End Sub

#End Region

#Region "Repeater Methods"

        Private SubrptObject_ItemDataBound(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptObject.ItemDataBound
            If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
                Dim CarouselName As String = DataBinder.Eval(e.Item.DataItem, "CarouselName")
                Dim ImageName AsString = DataBinder.Eval(e.Item.DataItem, "ImageName")
                Dim URL AsString = DataBinder.Eval(e.Item.DataItem, "URL")
                Dim Description AsString = DataBinder.Eval(e.Item.DataItem, "Description")
                Dim sCarousel AsString = ""
                Dim ltCarousel AsLiteral = DirectCast(e.Item.FindControl("ltCarousel"), Literal)

                If ItemActive <= ItemPerSlide Then
                    If ItemActive = 1 Then
                        sCarousel &= "<div class=""item active"">" & vbCrLf
                        sCarousel &= "<ul class=""thumbnails"">" & vbCrLf
                        'Slide += 1
                    End If
                    sCarousel &= "<li class=""span3"">" & vbCrLf
                    sCarousel &= "<div class=""thumbnail"">" & vbCrLf
                    sCarousel &= "<img width=""200px"" height=""200px"" src=""" & Page.ResolveUrl(ImageName) & """ alt="""" />" & vbCrLf
                    sCarousel &= "</div>"& vbCrLf
                    sCarousel &= "<div class=""caption"">" & vbCrLf
                    sCarousel &= "<h4>"& CarouselName & "</h4>"& vbCrLf
                    sCarousel &= "<p>"& Description & "</p>"
                    sCarousel &= "<a class=""btn btn-mini"" href=" & URL & ">&raquo; Read More</a>"& vbCrLf
                    sCarousel &= "</div>"& vbCrLf
                    sCarousel &= "</li>" & vbCrLf

                    If ItemActive = ItemPerSlide Then
                        sCarousel &= "</ul>" & vbCrLf
                        sCarousel &= "</div><!-- /Slide1 --> "& vbCrLf
                    End If
                Else
                    If ItemActive = (ItemPerSlide * Slide) + 1 Then
                        sCarousel &= "<div class=""item"">" & vbCrLf
                        sCarousel &= "<ul class=""thumbnails"">" & vbCrLf
                        Slide += 1
                    End If
                    sCarousel &= "<li class=""span3"">" & vbCrLf
                    sCarousel &= "<div class=""thumbnail"">" & vbCrLf
                    sCarousel &= "<img width=""200px"" height=""200px"" src=""" & Page.ResolveUrl(ImageName) & """ alt="""" />" & vbCrLf
                    sCarousel &= "</div>"& vbCrLf
                    sCarousel &= "<div class=""caption"">" & vbCrLf
                    sCarousel &= "<h4>"& CarouselName & "</h4>"& vbCrLf
                    sCarousel &= "<p>" & Description & "</p>" & vbCrLf
                    sCarousel &= "<a class=""btn btn-mini"" href=" & URL & ">&raquo; Read More</a>"& vbCrLf
                    sCarousel &= "</div>"& vbCrLf
                    sCarousel &= "</li>"& vbCrLf
                    If ItemActive = (ItemPerSlide * Slide) Then
                        sCarousel &= "</ul>" & vbCrLf
                        sCarousel &= "</div><!-- /Slide2 --> "& vbCrLf
                    End If
                End If
                ItemActive += 1
                ltCarousel.Text = sCarousel
            End If
        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
                    BindData()
                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

0 comments Blogger 0 Facebook

Post a Comment

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top