Wednesday, October 26, 2011

Asp.net - Image Gallery Using DataList in Asp.net

In this article i will show you how to use jQuery to show a larger image when user hovers thumbnail images from a asp.net Datalist control, also use hidden img control to cache the large image when page loads which improves the performance dramatically.


Let see how to bind images in a DataList Control and show large image when user move the mouse cursor to the image using JQuery.


Step 1
First you need to download latest AJAX control toolkit(September 2011 Release) from the following Link.
http://ajaxcontroltoolkit.codeplex.com/releases/view/74023

Step 2
Create a Web Application and give the Solution Name as SolImageGallery.


Step 3
Add Ajax control toolkit on Toolbox tab.


Step 4
Save images in Folder,Create a New Folder in the Solution and give folder name as Images,it is look like this


Click on Image for better view

Step 5
Add XML file in the App_Data folder and give the file name as ImageData.xml,it is look like this


Click on Image for better view


Step 6
The XML in the following example defines an XML document with a root node called Images. This root node contains one or more nodes called Image that include elements called ImageName and ImagePath,it's look like this




    Gaara
    ~/Images/Gaara.png
  

  
    Choji Akimichi
    ~/Images/Choji.png
  

  
    Jiraiya
    ~/Images/Jiraiya.jpg
  

  
    Kakashi Hatake
    ~/Images/Kakashi.png
  


    Kiba Inuzuka
    ~/Images/Kiba.png
  

    Naruto Uzumaki
    ~/Images/Naruto.jpg
  


     Neji Hyuuga
     ~/Images/Neji.jpg
  


     Rock Lee
    ~/Images/RockLee.jpg
  


     Sai
    ~/Images/Sai.jpg
  


  Shikamaru Nara
    ~/Images/Shikamaru.jpg
  


  Shino Aburame
    ~/Images/Shino.jpg
  


  Yamato
    ~/Images/Yamato.jpg
  



Step 7
Create an ImageEntity class in App_Code Folder,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class ImageEntity
{
    #region Property

    public String ImageName
    {
        get;
        set;

    }

    public String ImagePath
    {
        get;
        set;
    }

    #endregion
}


Step 8
Create a ImageView static class in a App_Code folder for retrieving data from XML document.it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;


public static class ImageView
{
    #region Methods

    public static List GetImagesData()
    {
        try
        {
            // Load Xml Document  

            String XmlFile = HttpContext.Current.Server.MapPath("App_Data/ImageData.xml");

            XDocument XDoc = XDocument.Load(XmlFile);

            // Query for retriving all Images data from XML  
            var Query = from Q in XDoc.Descendants("Image")
                        select new ImageEntity
                        {
                            ImageName = Q.Element("ImageName").Value,
                            ImagePath = Q.Element("ImagePath").Value
                        };

            // return images data  
          return Query.ToList<ImageEntity>();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }

    #endregion
}

Step 9
Add a ToolkitScriptManager control from Ajax toolkit inside the Div Tag,it is look like this
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>

This control allows you to replace the default <asp:scriptmanager> control behavior, and supports the ability to dynamically merge multiple client-side Javascript scripts into a single file that is downloaded to the client at runtime. 


Step 10
Create a CSS for view Large Image and Panel Control,it is look like this



Step 11
Drag a DataList control onto a page. Then, use the following code to set the RepeatColumns property to 4, and set the RepeatDirection property to vertical and set CellSpacing and cellpadding to 5,it is look like this
<asp:DataList ID="DataListImages" runat="server" RepeatColumns="4" RepeatDirection="Vertical" CellPadding="5" CellSpacing="5">
</asp:DataList>

Step 12
Use the following code to set the template in the DataList control to bind to a Image URL to image control and hidden image tag and Create Rounded corner panel with the help of AJAX RoundedCorners Extender,it is look like this

<ItemTemplate>

       <%--Rounded Corner Panel with AJAX RoundedCorner Extender--%>
       <asp:Panel ID="PnlImages" runat="server" CssClass="RoundedCorner">
      
       <div class="RoundedContent">
        
        <a class="ImagePreview" rel="<%#Eval("ImagePath")%>">
         
         <%--Bind Image Path in Image Control--%>
         <asp:Image ID="ImgGallery" runat="server" ImageUrl="<%#Bind('ImagePath')%>" ImageAlign="Middle" Width="150" Height="150" CssClass="ImagePreview" />
        
           <%-- Hidden Image control for caching the images--%>
         <img id="<%#Eval("ImagePath")%>" src="<%#Eval("ImagePath")%>" alt="" style="display:none"/>

        </a>
        
        <%--Bind Image Name in Label--%>
        <asp:Label ID="lblImageName" runat="server" Text='<%#Eval("ImageName")%>' style="color:Red"></asp:Label>

         </div>
    
      </asp:Panel>

                        <%--Add Rounded Corner Extender to the Panel Control--%>
        <asp:RoundedCornersExtender ID="Pnl_RoundedCorner" runat="server" TargetControlID="PnlImages" Corners="All" Radius="15"></asp:RoundedCornersExtender>

 
   </ItemTemplate>


Finally it is look like this
<asp:DataList ID="DataListImages" runat="server" RepeatColumns="4" RepeatDirection="Vertical"
  CellPadding="5" CellSpacing="5">
   <ItemTemplate>

       <%--Rounded Corner Panel with AJAX RoundedCorner Extender--%>
       <asp:Panel ID="PnlImages" runat="server" CssClass="RoundedCorner">
      
       <div class="RoundedContent">
        
        <a class="ImagePreview" rel="<%#Eval("ImagePath")%>">
         
         <%--Bind Image Path in Image Control--%>
         <asp:Image ID="ImgGallery" runat="server" ImageUrl="<%#Bind('ImagePath')%>" ImageAlign="Middle" Width="150" Height="150" CssClass="ImagePreview" />
        
           <%-- Hidden Image control for caching the images--%>
         <img id="<%#Eval("ImagePath")%>" src="<%#Eval("ImagePath")%>" alt="" style="display:none"/>

        </a>
        
        <%--Bind Image Name in Label--%>
        <asp:Label ID="lblImageName" runat="server" Text='<%#Eval("ImageName")%>' style="color:Red"></asp:Label>

         </div>
    
      </asp:Panel>

                        <%--Add Rounded Corner Extender to the Panel Control--%>
        <asp:RoundedCornersExtender ID="Pnl_RoundedCorner" runat="server" TargetControlID="PnlImages" Corners="All" Radius="15"></asp:RoundedCornersExtender>

 
   </ItemTemplate>
  </asp:DataList>


Click on Image for better view


Step 13
Create a Script file for view large image when user move to the mouse cursor to the image using JQuery,give the file name as LargeImagePreview.js
this.LargeImagePreview = function () {

 // these 2 variable determine popup's distance from the cursor
 // you might want to adjust to get the right result
 xOffset = 10;
 yOffset = 10;

 // View Large Image on Mouse Hover Event
 $("a.ImagePreview").hover(function (e) {
  //Get rel Data from hidden Image control.
  var ImgHidden = $(this).attr('rel');

  // Change String 
  // For Example - ~/Images/Kakashi.jpg to Images/Kakashi.jpg
  var ImgSrc = ImgHidden.replace("~/", "");

  // Bind Images in Paragraph tag
  $("body").append("<p id='ImagePreview'><img src='" + ImgSrc + "' alt='loading...' /></p>");

  $("#ImagePreview")
   .css("top", (e.pageY - xOffset) + "px")
   .css("left", (e.pageX + yOffset) + "px")
   .fadeIn("fast");
 },
 function () {
  $("#ImagePreview").remove();
 });
$("a.ImagePreview").mousemove(function (e) {
  $("#ImagePreview")
   .css("top", (e.pageY - xOffset) + "px")
   .css("left", (e.pageX + yOffset) + "px");
 });

};

Step 14
Add jQuery file Reference inside the head tag of the page and call LargeImagePreview function on page load event,it is look like this

 

 

Full .Aspx Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>



<!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 */
  Body
  {
   background-color:Gray;
   }
  
  
  /** for view Large Image */ 
  #ImagePreview
  {
   position:absolute;
   border:1px solid #ccc;
   background:#333;
   padding:1px;
   display:none;
   color:#fff;
   }
 
 /* Rounded Corner for Panel*/
 .RoundedCorner
 {
  background-color:White;
  width:170px;
  }
  
  .RoundedContent 
   {            
    text-align:center;
    padding:10px;                       
    }
   

 </style>

 <script language="javascript" src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
 <script language="javascript" src="Scripts/LargeImagePreview.js" type="text/javascript"></script>

 <script language="javascript" type="text/javascript">

  $(document).ready(function () {
   
   // Start the Script on Page Load
   LargeImagePreview();
  }
   );

 </script>

</head>
<body>

 <form id="form1" runat="server">
 <div>
  <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
  </asp:ToolkitScriptManager>

  <asp:DataList ID="DataListImages" runat="server" RepeatColumns="4" RepeatDirection="Vertical"
  CellPadding="5" CellSpacing="5">
   <ItemTemplate>

       <%--Rounded Corner Panel with AJAX RoundedCorner Extender--%>
       <asp:Panel ID="PnlImages" runat="server" CssClass="RoundedCorner">
      
       <div class="RoundedContent">
        
        <a class="ImagePreview" rel="<%#Eval("ImagePath")%>">
         
         <%--Bind Image Path in Image Control--%>
         <asp:Image ID="ImgGallery" runat="server" ImageUrl="<%#Bind('ImagePath')%>" ImageAlign="Middle" Width="150" Height="150" CssClass="ImagePreview" />
        
           <%-- Hidden Image control for caching the images--%>
         <img id="<%#Eval("ImagePath")%>" src="<%#Eval("ImagePath")%>" alt="" style="display:none"/>

        </a>
        
        <%--Bind Image Name in Label--%>
        <asp:Label ID="lblImageName" runat="server" Text='<%#Eval("ImageName")%>' style="color:Red"></asp:Label>

         </div>
    
      </asp:Panel>

      <%--Add Rounded Corner Extender to the Panel Control--%>
        <asp:RoundedCornersExtender ID="Pnl_RoundedCorner" runat="server" TargetControlID="PnlImages" Corners="All" Radius="15"></asp:RoundedCornersExtender>

 
   </ItemTemplate>
  </asp:DataList>

 </div>
 </form>
</body>
</html>




Step 15
Now Bind Image data in DataList Control,it's look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            if (IsPostBack == false)
            {
                // Call Bind Image Data function on Page Load Event
                BindImageData();
            }

            
        }
        catch (Exception)
        { 
        }
    }

    #region Methods

    /// 
    ///  Bind Image Data into DataList Control
    /// 
    private void BindImageData()
    {
        try
        {
            // Store Data In List Object
           List<ImageEntity> ListObj = ImageView.GetImagesData();

            // Check the List Objetc is null or not
            if (ListObj != null)
            {
                // Check list Object count
                if (ListObj.Count > 0)
                {
                    // Bind Data in DataList Control
                    DataListImages.DataSource = ListObj;
                    DataListImages.DataBind();
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }

    #endregion
}


Run the Project.


Output


Click on Image for better view


Mouse Over Event






Download
Download Source Code

10 comments:

  1. Nice Article.
    Thanks for sharing Code.

    Vikas Patil..

    ReplyDelete
  2. Thank uuuu....
    Madhuri

    ReplyDelete
  3. how we can show the image on center of the page

    ReplyDelete
    Replies
    1. Error comes in step 8 with following code

      Delete
    2. Please Download Source Code from this article and then view the code.There is bug in Code Highlighter in my blog.
      The Solution is working Properly.Don't Worry about that Just Download Source Code.

      Delete
    3. How can I change the Mouse Over Event to OnClick?

      Delete
  4. Nice code.
    can we use listview to show data in listview and gallaryview?

    ReplyDelete