Sunday, January 11, 2009

Bind a Class to a Datasource (instead of a SQL, LINQ etc statement)

Hi All, 

The fact is, I needed to quickly bind an Accordion form the AJAX Control Kit to a simple list of objects, I didn't want to create a Table in the DB, simply because it wasn't necessary, I didn't want to write LINQ because it wan't part of my entity model. All I had was a Collection of anonymous types called (items) and I wanted to bind it to an accordian. Here is how you do it : 

Step 1 :  Create a new class and dump this in there.

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

namespace WebSiteManagerz
    public class AccordianItems
        public static ArrayList FetchItems()
            ArrayList Items = new ArrayList();
            Items .Add(new { Name = "Full packaged solution including Design, Development, Hosting and Maintenance", ImageUrl = "img/icon1.gif" });
            Items .Add(new { Name = "A vast range of different technologies catered for you needs", ImageUrl = "img/icon2.gif" });
            Items .Add(new { Name = "A talented team of experienced web professionals, dedicated to your project", ImageUrl = "img/icon3.gif" });
            Items .Add(new { Name = "Different levels of client interaction, from the \"Just get it done\" approach, to a much more intimate client experience", ImageUrl = "img/icon4.gif" });
            return Items ;

Step 2: In your ASPX page, here is what you should add :

<asp:ObjectDataSource ID="Items" runat="server" SelectMethod="FetchItems" TypeName="WebSiteManagerz.AccordianItems" /> <cc1:Accordion ID="accordion" runat="server" FadeTransitions="false" FramesPerSecond="100" TransitionDuration="250" CssClass="accordion" HeaderCssClass="header" ContentCssClass="content" RequireOpenedPane="True" AutoSize="Fill"> <Panes> <cc1:AccordionPane ID="mail" runat="server"> <Header> <div> <span>What we offer?</span> </div> </Header> <Content> <asp:ListView ID="pane1" runat="server" DataSourceID="Items"> <LayoutTemplate> <ul> <li id="someid" runat="server" /> </ul> </LayoutTemplate> <ItemTemplate> <li style='background-image: url(<%# Eval("ImageUrl") )'> <%# Eval("Name") %></li> </ItemTemplate> </asp:ListView> </Content> </cc1:AccordionPane> </Panes> </cc1:Accordion>

No comments: