Friday, June 24, 2011

AJAX - DataBinding AJAX Accordion Control

In this article, we will see how to dynamically pull data from the database and display it using an ASP.NET AJAX Accordion control. We will be using the data from the Employees table of the Northwind database.


Step 1
Download northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en

Step 2
Attach a northwind database into MS-SQL server

Step 3
Create a Web application and give solution name as SolBindingAJAX_accrodian.



Step 4
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 5
Create a CSS for accordion control,Add a new folder in the solution and give the folder name as CSS,Select the CSS folder,right click on Add new Item,select Style Sheet from installed Visual Studio templates and click on add button.
/* Accordion Simple CSS */

/* For Header*/ 
.AccordionHeader
{
    border: 2px solid #A5A5A5;
    color: white;
    background-color:Gray;
 font-family: Arial, Sans-Serif;
 font-size: 12px;
 font-weight: bold;
    padding: 5px;
    margin-top: 5px;
    cursor: pointer;
}

/* For Content*/
.AccordionContent
{
    background-color:Teal;
    border: 1px solid #2F4F4F;
    border-top: none;
    padding: 5px;
    padding-top: 10px;
}

Step 6
Attach a CSS inside the Head Section,it is look like this
<head runat="server">

    <title>AJAX Accordian Binding Examle</title>



    <link href="CSS/StyleSheet.css" type="text/css" rel="Stylesheet" />



</head>

Step 7
Add a Accordion Control from Ajax toolkit,it is look like this
<asp:Accordion ID="AccordianBind" headercssclass="AccordionHeader"

        contentcssclass="AccordionContent" runat="server" FadeTransitions="true"  TransitionDuration="400"

         SelectedIndex="-1" RequireOpenedPane="false" FramesPerSecond="50" >



         <HeaderTemplate>

             

             

         </HeaderTemplate>



         <ContentTemplate>

            

            

         </ContentTemplate>



         </asp:Accordion>


There are the following basic properties of Accordion control:

1. FadeTransitions
    True to use the fading transition effect, false for standard transitions.

2. TransitionDuration
     Number of milliseconds to animate the transitions.

3.  HeaderCssClass 
     Name of the CSS class to use for the headers. This can be either applied to the Accordion  as a default for all AccordionPanes, or an individual AccordionPane.

4.  ContentCssClass
     Name of the CSS class to use for the content. This can be either applied to the Accordion as a default for all AccordionPanes, or an individual AccordionPane.

5.  SelectedIndex
     The AccordionPane to be initially visible.

6.  RequireOpenedPane
     Prevent closing the currently opened pane when its header is clicked (which ensures one pane is always open). The default value is true.

7.  FramesPerSecond
     Number of frames per second used in the transition animations. 



Step 8
Now display the records from the Employees table in the Accordion control. The <HeaderTemplate> will contain the Employee Name and the <ContentTemplate> will contain the Employee Notes information,it is look like this


<asp:Accordion ID="AccordianBind" headercssclass="AccordionHeader"
        contentcssclass="AccordionContent" runat="server" FadeTransitions="true"  TransitionDuration="400"
         SelectedIndex="-1" RequireOpenedPane="false" FramesPerSecond="50" >

         <HeaderTemplate>
             
             <b><%#DataBinder.Eval(Container.DataItem,"FirstName")%></b>
              <b><%#DataBinder.Eval(Container.DataItem,"LastName") %></b>  

         </HeaderTemplate>

         <ContentTemplate>
            
            <h3>
                <%#DataBinder.Eval(Container.DataItem,"Notes")  %>
            </h3>

         </ContentTemplate>

         </asp:Accordion>

If you observe, we have used the DataBinder.Eval() to retrieve the FirstName and LastName in a bold tag, which is to be displayed in the <HeaderTemplate>. When the user clicks on this link, the ContentTemplate appears which contains details about the Employee.


Step 9
Add a connectionstring on web.config file,it is look like this


<connectionStrings>
  <add name="NorthwindConnectionString" connectionString="Data Source=SHREE\SHREE;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
 </connectionStrings>

Step 10
Add app_code folder in the solution and add a new folder inside the app_code folder and give folder name as ORD,it is look like this




Click on Image for Better View

Step 11
Add a Linq to Sql class,Select the ORD folder,right click on Add new Item,selectLINQ to SQL classes from installed Visual Studio templates and name it NorthwindDC and click on add button,it is look like this




Click on Image for Better View


Step 12
Open a O/R Designer by double click on NorthwindDC.dbml,it is look like this




Click on Image for Better View




Click on Image for Better View


Visual stdio provides an object-relational mapping designer,called the O/R Designer which allows you to visually design the object to database mapping.


Step 13

Create a Employee object.
in this example we have to work with employees table from the northwind database,create a employee object that will use LINQ to SQL to map to this table.go to the server explorer,select northwind database,go to the tables and select Employees table,it is look like this





Click on Image for Better View


Drag and drop Employee table from Server explorer onto the design surface of the O/R Designer,it is look like this




Click on Image for Better View


Step 14
Create a Employee static class in app_code folder for retriving an employee data from database,it is look like this


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

public static class Employee
{
    #region Bind EmployeeData
    /// 
    ///  Get Employee Data
    /// 
    /// List
    public static List<ord.employee> GetEmployeeData()
    {
        try
        {
            ORD.NortwindDCDataContext DC = new ORD.NortwindDCDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString.Trim());

            var Query = (from Q in DC.Employees
                         select new ORD.Employee
                         {
                             FirstName = Q.FirstName,
                             LastName = Q.LastName,
                             Notes = Q.Notes
                         }
                           ).ToList<ord.employee>();

            return Query;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #endregion
}

Step 15
Bind the employee data in Accordion Control.it is look like this


 protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                BindAccordianEmployeeData(); 
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #region Bind Data to Ajax Accrodian Control

    private void BindAccordianEmployeeData()
    {
        try
        {
           List<ord.employee> ListEmployee = Employee.GetEmployeeData();

            if (ListEmployee.Count > 0)
            {
                AccordianBind.DataSource = ListEmployee;
                AccordianBind.DataBind();
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #endregion

Run the Project.


Output




Click on Image for Better View


Full Code


1. .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>AJAX Accordian Binding Examle</title>

    <link href="CSS/StyleSheet.css" type="text/css" rel="Stylesheet" />

</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <asp:toolkitscriptmanager ID="Toolkitscriptmanager1" runat="server">
        </asp:toolkitscriptmanager>

        <asp:Accordion ID="AccordianBind" headercssclass="AccordionHeader"
        contentcssclass="AccordionContent" runat="server" FadeTransitions="true"  TransitionDuration="400"
         SelectedIndex="-1" RequireOpenedPane="false" FramesPerSecond="50" >

         <HeaderTemplate>
             
             <b><%#DataBinder.Eval(Container.DataItem,"FirstName")%></b>
              <b><%#DataBinder.Eval(Container.DataItem,"LastName") %></b>  

         </HeaderTemplate>

         <ContentTemplate>
            
            <h3>
                <%#DataBinder.Eval(Container.DataItem,"Notes")  %>
            </h3>

         </ContentTemplate>

         </asp:Accordion>
        
    </div>
    </form>
</body>
</html>


2. Code behind 
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)
            {
                BindAccordianEmployeeData(); 
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #region Bind Data to Ajax Accrodian Control

    private void BindAccordianEmployeeData()
    {
        try
        {
           List<ord.employee> ListEmployee = Employee.GetEmployeeData();

            if (ListEmployee.Count > 0)
            {
                AccordianBind.DataSource = ListEmployee;
                AccordianBind.DataBind();
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }

    #endregion
}

Download
Download Source Code

No comments:

Post a Comment