Create Image gallery with DataList from Database using jQuery masonry Plugin in ASP.Net

Last Reply one year ago By pandeyism

Posted one year ago

I wanted to create image grid like this one below

https://bootsnipp.com/snippets/featured/masonry-image-gallery

i want to creat image grid from database using Ajax

CSS

 

body {
    font-family: sans-serif;
}
#container {
    background: #DDD;
    max-width: 1400px;
}
.item {
    width: 200px;
    float: left;
}
.item img {
    display: block;
    width: 100%;
}
button {
    font-size: 18px;
}
.container{
    width:100%;
}

HTML

 

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->

<div class="container">
<h1>Masonry + imagesLoaded, iteratively reveal items</h1>

<div id="container"></div>
<div id="images">
    <div class="item">
        <img src="http://lorempixel.com/425/299/nature">
    </div>
    <div class="item">
        <img src="http://lorempixel.com/190/292/nature">
    </div>
    <div class="item">
        <img src="http://lorempixel.com/520/329/nature">
    </div>
    <div class="item">
        <img src="http://lorempixel.com/404/176/nature">
    </div>
    <div class="item">
        <img src="http://lorempixel.com/530/290/nature">
    </div>
    <div class="item">
        <img src="http://lorempixel.com/228/200/nature">
    </div>
    <div class="item">
        <img src="http://lorempixel.com/207/316/nature">
    </div>
    <div class="item">
        <img src="http://lorempixel.com/435/162/nature">
    </div>
    <div class="item">
        <img src="http://lorempixel.com/376/175/nature">
    </div>
    <div class="item">
        <img src="http://lorempixel.com/508/338/nature">
    </div>
    <div class="item">
        <img src="http://lorempixel.com/404/389/nature">
    </div>
    <div class="item">
        <img src="http://lorempixel.com/216/304/nature">
    </div>
</div>
<p>
    <button id="load-images">Load images</button>
    
    <script src="//masonry.desandro.com/masonry.pkgd.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/3.0.4/jquery.imagesloaded.js"></script>
    
    
    
    </div>
    
    
    
    
    
</p>

JQUERY

 

    $(function () {

    var $container = $('#container').masonry({
        itemSelector: '.item',
        columnWidth: 200
    });

    // reveal initial images
    $container.masonryImagesReveal($('#images').find('.item'));
});

$.fn.masonryImagesReveal = function ($items) {
    var msnry = this.data('masonry');
    var itemSelector = msnry.options.itemSelector;
    // hide by default
    $items.hide();
    // append to container
    this.append($items);
    $items.imagesLoaded().progress(function (imgLoad, image) {
        // get item
        // image is imagesLoaded class, not <img>, <img> is image.img
        var $item = $(image.img).parents(itemSelector);
        // un-hide item
        $item.show();
        // masonry does its thing
        msnry.appended($item);
    });

    return this;
};

 

Posted one year ago

Hi micah,

Will you please let me know why you want to bind using ajax?

Without using aja you can simpley bind the inages from database and apply the plugin.

Refer the below example.

HTML

<div class="container">
    <h1>
        Masonry + imagesLoaded, iteratively reveal items</h1>
    <asp:DataList ID="dlImages" runat="server" RepeatLayout="Table" RepeatColumns="3"
        CellPadding="2" CellSpacing="20">
        <ItemTemplate>
            <div id="images">
                <div class="item">
                    <img class="image" src='<%# Eval("ImageUrl") %>' alt="" />
                </div>
            </div>
        </ItemTemplate>
    </asp:DataList>
</div>
<style type="text/css">
    body
    {
        font-family: sans-serif;
    }
    #container
    {
        background: #DDD;
        max-width: 1400px;
    }
    .item
    {
        width: 200px;
        float: left;
    }
    .item img
    {
        display: block;
        width: 100%;
    }
    button
    {
        font-size: 18px;
    }
    .container
    {
        width: 100%;
    }
</style>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="//masonry.desandro.com/masonry.pkgd.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/3.0.4/jquery.imagesloaded.js"></script>
<script type="text/javascript">
    $(function () {
        var $container = $('#images').masonry({
            itemSelector: '.item',
            columnWidth: 200
        });

        // reveal initial images
        //$container.masonryImagesReveal($('#images').find('.item'));
    });

    $.fn.masonryImagesReveal = function ($items) {
        var msnry = this.data('masonry');
        var itemSelector = msnry.options.itemSelector;
        // hide by default
        $items.hide();
        // append to container
        this.append($items);
        $items.imagesLoaded().progress(function (imgLoad, image) {
            // get item
            // image is imagesLoaded class, not <img>, <img> is image.img
            var $item = $(image.img).parents(itemSelector);
            // un-hide item
            $item.show();
            // masonry does its thing
            msnry.appended($item);
        });

        return this;
    };
</script>

Namespaces

using System.Data;
using System.Configuration;
using System.Data.SqlClient;

C#

protected void Page_Load(object sender, EventArgs e)
{
    string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        SqlCommand cmd = new SqlCommand("SELECT * FROM ImageSlider", con);
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds, "Images");

                dlImages.DataSource = ds;
                dlImages.DataBind();
            }
        }
    }
}

Screenshot


Posted one year ago

Hi micah,

Please refer below sample.

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
    body
    {
        font-family: sans-serif;
    }
    #container
    {
        background: #DDD;
        max-width: 1400px;
    }
    .item
    {
        width: 200px;
        float: left;
    }
    .item img
    {
        display: block;
        width: 100%;
    }
    button
    {
        font-size: 18px;
    }
    .container
    {
        width: 100%;
    }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:FileUpload ID="fuGrid" runat="server" />
    <asp:Button ID="btnUpload" runat="server" Text="Submit" OnClick="btnUpload_Click" />
    <div class="container">
        <h1>
            Masonry + imagesLoaded, iteratively reveal items</h1>
        <asp:DataList ID="dlImages" runat="server" RepeatLayout="Table" RepeatColumns="3">
            <ItemTemplate>
                <div id="images">
                    <div class="item">
                        <img class="image" src='<%# Eval("Path") %>' alt="" />
                    </div>
                </div>
            </ItemTemplate>
        </asp:DataList>
    </div>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" />
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="//masonry.desandro.com/masonry.pkgd.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/3.0.4/jquery.imagesloaded.js"></script>
<script type="text/javascript">
    $(function () {
        var $container = $('#images').masonry({
            itemSelector: '.item',
            columnWidth: 200
        });

        // reveal initial images
        //$container.masonryImagesReveal($('#images').find('.item'));
    });

    $.fn.masonryImagesReveal = function ($items) {
        var msnry = this.data('masonry');
        var itemSelector = msnry.options.itemSelector;
        // hide by default
        $items.hide();
        // append to container
        this.append($items);
        $items.imagesLoaded().progress(function (imgLoad, image) {
            // get item
            // image is imagesLoaded class, not <img>, <img> is image.img
            var $item = $(image.img).parents(itemSelector);
            // un-hide item
            $item.show();
            // masonry does its thing
            msnry.appended($item);
        });

        return this;
    };
</script>

Namespaces

C#

using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;

VB.Net

Imports System.IO
Imports System.Data.SqlClient
Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            SqlCommand cmd = new SqlCommand("SELECT * FROM tblFilesPath", con);
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds);
                    dlImages.DataSource = ds;
                    dlImages.DataBind();
                }
            }
        }
    }
}

protected void btnUpload_Click(object sender, EventArgs e)
{
    string filename = Path.GetFileName(fuGrid.PostedFile.FileName);
    fuGrid.PostedFile.SaveAs(Server.MapPath("~/image/") + filename);
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        string query = "insert into tblFilesPath values (@Name, @Path)";
        using (SqlCommand cmd = new SqlCommand(query))
        {
            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@Name", filename);
            cmd.Parameters.AddWithValue("@Path", "image/" + filename);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    Response.Redirect(Request.Url.AbsoluteUri);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not Me.IsPostBack Then
        Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As SqlConnection = New SqlConnection(strConnString)
            Dim cmd As SqlCommand = New SqlCommand("SELECT * FROM tblFilesPath", con)
            Using sda As SqlDataAdapter = New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using ds As DataSet = New DataSet()
                    sda.Fill(ds)
                    dlImages.DataSource = ds
                    dlImages.DataBind()
                End Using
            End Using
        End Using
    End If
End Sub

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim filename As String = Path.GetFileName(fuGrid.PostedFile.FileName)
    fuGrid.PostedFile.SaveAs(Server.MapPath("~/image/") & filename)
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(constr)
        Dim query As String = "insert into tblFilesPath values (@Name, @Path)"
        Using cmd As SqlCommand = New SqlCommand(query)
            cmd.Connection = con
            cmd.Parameters.AddWithValue("@Name", filename)
            cmd.Parameters.AddWithValue("@Path", "image/" & filename)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Using

    Response.Redirect(Request.Url.AbsoluteUri)
End Sub

Screenshot

Database record and project folder after insert

Output