Implement Bootstrap Carousel (Image Gallery) from database using jQuery AJAX in ASP.Net

Last Reply 7 months ago By dharmendr

Posted 7 months ago

i have a bootstrap carousel ..

how can i dynamically bind images from database to the below carousel using ajax json jquery web method.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  <style>
  .carousel-inner > .item > img,
  .carousel-inner > .item > a > img {
    width: 70%;
    margin: auto;
  }
  </style>
</head>
<body>

<div class="container">
  <br>
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
      <li data-target="#myCarousel" data-slide-to="2"></li>
      <li data-target="#myCarousel" data-slide-to="3"></li>
    </ol>
    <!-- Wrapper for slides -->
    <div class="carousel-inner" role="listbox">
      <div class="item active">
        <img src="img_chania.jpg" alt="Chania" width="460" height="345">
        <div class="carousel-caption">
          <h3>Chania</h3>
          <p>The atmosphere in Chania has a touch of Florence and Venice.</p>
        </div>
      </div>
      <div class="item">
        <img src="img_chania2.jpg" alt="Chania" width="460" height="345">
        <div class="carousel-caption">
          <h3>Chania</h3>
          <p>The atmosphere in Chania has a touch of Florence and Venice.</p>
        </div>
      </div>    
      <div class="item">
        <img src="img_flower.jpg" alt="Flower" width="460" height="345">
        <div class="carousel-caption">
          <h3>Flowers</h3>
          <p>Beautiful flowers in Kolymbari, Crete.</p>
        </div>
      </div>  
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
      <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</div>
</body>
</html>

 

Posted 7 months ago

Hi jochk12345,

Check this example. Now please take its reference and correct your code.

Database

For this example i have used two table tblFiles and tblFilesPath with the following table structure and data.

--==========tblFiles==========--
CREATE TABLE [dbo].[tblFiles](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](50) NOT NULL,
	[ContentType] [nvarchar](200) NOT NULL,
	[Data] [varbinary](max) NOT NULL,
 CONSTRAINT [PK_tblFiles] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[tblFiles] ON 
GO
INSERT [dbo].[tblFiles] ([id], [Name], [ContentType], [Data]) VALUES (1, N'Chrysanthemum.jpg', N'image/jpeg', 0xFFD8FFE0...)
GO
INSERT [dbo].[tblFiles] ([id], [Name], [ContentType], [Data]) VALUES (2, N'Desert.jpg', N'image/jpeg', 0xFFD8FFE0...)
GO
INSERT [dbo].[tblFiles] ([id], [Name], [ContentType], [Data]) VALUES (3, N'Hydrangeas.jpg', N'image/jpeg', 0xFFD8FFE0...)
GO
INSERT [dbo].[tblFiles] ([id], [Name], [ContentType], [Data]) VALUES (4, N'Lighthouse.jpg', N'image/jpeg', 0xFFD8FFE0...)
GO
INSERT [dbo].[tblFiles] ([id], [Name], [ContentType], [Data]) VALUES (5, N'Jellyfish.jpg', N'image/jpeg', 0xFFD8FFE0...)
GO
INSERT [dbo].[tblFiles] ([id], [Name], [ContentType], [Data]) VALUES (6, N'Koala.jpg', N'image/jpeg', 0xFFD8FFE0...)
GO
SET IDENTITY_INSERT [dbo].[tblFiles] OFF
GO
--==========tblFilesPath==========--
CREATE TABLE [dbo].[tblFilesPath](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Path] [nvarchar](200) NOT NULL,
 CONSTRAINT [PK_tblFilesPath] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[tblFilesPath] ON 
GO
INSERT [dbo].[tblFilesPath] ([Id], [Name], [Path]) VALUES (1, N'Chrysanthemum.jpg', N'Images/Chrysanthemum.jpg')
GO
INSERT [dbo].[tblFilesPath] ([Id], [Name], [Path]) VALUES (2, N'Desert.jpg', N'Images/Desert.jpg')
GO
INSERT [dbo].[tblFilesPath] ([Id], [Name], [Path]) VALUES (3, N'Hydrangeas.jpg', N'Images/Hydrangeas.jpg')
GO
INSERT [dbo].[tblFilesPath] ([Id], [Name], [Path]) VALUES (4, N'Jellyfish.jpg', N'Images/Jellyfish.jpg')
GO
INSERT [dbo].[tblFilesPath] ([Id], [Name], [Path]) VALUES (5, N'Koala.jpg', N'Images/Koala.jpg')
GO
INSERT [dbo].[tblFilesPath] ([Id], [Name], [Path]) VALUES (6, N'Lighthouse.jpg', N'Images/Lighthouse.jpg')
GO
INSERT [dbo].[tblFilesPath] ([Id], [Name], [Path]) VALUES (7, N'Penguins.jpg', N'Images/Penguins.jpg')
GO
SET IDENTITY_INSERT [dbo].[tblFilesPath] OFF

For inserting binary data you can refer below article.

Display Binary Image from database in ASP.Net GridView control using C# and VB.Net

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Bootstrap Carousel</title>
    <style type="text/css">
        .carousel-container
        {
            width: 250px;
        }
    </style>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Default.aspx/GetBinaryImages",
                dataType: "json",
                success: function (data) {
                    var response = '';
                    var indicator = '';
                    for (var i = 0; i < data.d.length; i++) {
                        response += '<div class="item">' +
                        '<img src="data:image/jpg;base64,' + data.d[i].Image + '" alt="' + data.d[i].Name + '" width="460px" height="100px">' +
                        '<div class="carousel-caption">' +
                        '<h3>' + data.d[i].Name.split('.')[0] + '</h3>' +
                        '</div></div>';
                        indicator += '<li data-target="#myCarouselBinary" data-slide-to="' + i + '"></li>';
                    }
                    $('#dvBinary #items').append(response);
                    $('#dvBinary #indicators').append(indicator);
                    $('#dvBinary .item').first().addClass('active');
                    $('#dvBinary .carousel-indicators > li').first().addClass('active');
                    $("#dvBinary #myCarouselBinary").carousel();
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Default.aspx/GetPathImages",
                dataType: "json",
                success: function (data) {
                    var response = '';
                    var indicator = '';
                    for (var i = 0; i < data.d.length; i++) {
                        response += '<div class="item">' +
                        '<img src="' + data.d[i].Image + '" alt="' + data.d[i].Name + '" width="460px" height="100px">' +
                        '<div class="carousel-caption">' +
                        '<h3>' + data.d[i].Name.split('.')[0] + '</h3>' +
                        '</div></div>';
                        indicator += '<li data-target="#myCarouselPath" data-slide-to="' + i + '"></li>';
                    }
                    $('#dvPath #items').append(response);
                    $('#dvPath #indicators').append(indicator);
                    $('#dvPath .item').first().addClass('active');
                    $('#dvPath .carousel-indicators > li').first().addClass('active');
                    $("#dvPath #myCarouselPath").carousel();
                },
                error: function (response) {
                    alert(response.responseText);
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>
                <div class="container" id="dvBinary">
                    <h3>Using Binary Data</h3>
                    <hr />
                    <div class="carousel-container">
                        <div id="myCarouselBinary" class="carousel slide" data-ride="carousel">
                            <!-- Indicators -->
                            <ol class="carousel-indicators" id="indicators">
                            </ol>
                            <!-- Wrapper for slides -->
                            <div class="carousel-inner" id="items" role="listbox">
                            </div>
                            <!-- Left and right controls -->
                            <div class="carousel-controls">
                                <a class="carousel-control left" href="#myCarouselBinary" data-slide="prev">
                                    <span class="glyphicon glyphicon-chevron-left"></span>
                                    <span class="sr-only">Previous</span>
                                </a>
                                <a class="carousel-control right" href="#myCarouselBinary" data-slide="next">
                                    <span class="glyphicon glyphicon-chevron-right"></span>
                                    <span class="sr-only">Next</span>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </td>
            <td>
                <div class="container" id="dvPath">
                    <h3>Using File Path</h3>
                    <hr />
                    <div class="carousel-container">
                        <div id="myCarouselPath" class="carousel slide" data-ride="carousel">
                            <!-- Indicators -->
                            <ol class="carousel-indicators" id="indicators">
                            </ol>
                            <!-- Wrapper for slides -->
                            <div class="carousel-inner" id="items" role="listbox">
                            </div>
                            <!-- Left and right controls -->
                            <div class="carousel-controls">
                                <a class="carousel-control left" href="#myCarouselPath" data-slide="prev">
                                    <span class="glyphicon glyphicon-chevron-left"></span>
                                    <span class="sr-only">Previous</span> 
                                </a>
                                <a class="carousel-control right" href="#myCarouselPath" data-slide="next">
                                    <span class="glyphicon glyphicon-chevron-right"></span>
                                    <span class="sr-only">Next</span> 
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Namespaces

C#

using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Services;

VB.Net

Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Services

Code

C#

[WebMethod]
public static List<ImageSlider> GetBinaryImages()
{
    List<ImageSlider> products = new List<ImageSlider>();
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT * FROM tblFiles";
    using (SqlConnection con = new SqlConnection(conString))
    {
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader sdr = cmd.ExecuteReader();
        while (sdr.Read())
        {
            products.Add(new ImageSlider
            {
                Id = Convert.ToInt32(sdr["Id"]),
                Name = sdr["Name"].ToString(),
                Image = Convert.ToBase64String((byte[])sdr["Data"], 0, ((byte[])sdr["Data"]).Length)
            });
        }
        con.Close();
    }

    return products;
}

[WebMethod]
public static List<ImageSlider> GetPathImages()
{
    List<ImageSlider> products = new List<ImageSlider>();
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT * FROM tblFilesPath";
    using (SqlConnection con = new SqlConnection(conString))
    {
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader sdr = cmd.ExecuteReader();
        while (sdr.Read())
        {
            products.Add(new ImageSlider
            {
                Id = Convert.ToInt32(sdr["Id"]),
                Name = sdr["Name"].ToString(),
                Image = sdr["Path"].ToString()
            });
        }
        con.Close();
    }

    return products;
}

public class ImageSlider
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Image { get; set; }
}

VB.Net

<WebMethod()>
Public Shared Function GetBinaryImages() As List(Of ImageSlider)
    Dim products As List(Of ImageSlider) = New List(Of ImageSlider)()
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT * FROM tblFiles"
    Using con As SqlConnection = New SqlConnection(conString)
        Dim cmd As SqlCommand = New SqlCommand(query, con)
        con.Open()
        Dim sdr As SqlDataReader = cmd.ExecuteReader()
        While sdr.Read()
            products.Add(New ImageSlider With {
                .Id = Convert.ToInt32(sdr("Id")),
                .Name = sdr("Name").ToString(),
                .Image = Convert.ToBase64String(CType(sdr("Data"), Byte()), 0, (CType(sdr("Data"), Byte())).Length)
            })
        End While
        con.Close()
    End Using
    Return products
End Function

<WebMethod()>
Public Shared Function GetPathImages() As List(Of ImageSlider)
    Dim products As List(Of ImageSlider) = New List(Of ImageSlider)()
    Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT * FROM tblFilesPath"
    Using con As SqlConnection = New SqlConnection(conString)
        Dim cmd As SqlCommand = New SqlCommand(query, con)
        con.Open()
        Dim sdr As SqlDataReader = cmd.ExecuteReader()
        While sdr.Read()
            products.Add(New ImageSlider With {
                .Id = Convert.ToInt32(sdr("Id")),
                .Name = sdr("Name").ToString(),
                .Image = sdr("Path").ToString()
            })
        End While
        con.Close()
    End Using
    Return products
End Function

Public Class ImageSlider
    Public Property Id As Integer
    Public Property Name As String
    Public Property Image As String
End Class

Screenshot