Upgrading from the AjaxControlToolkit Collapsible Panel using jQuery in Asp.Net WebForms: Remembering the Panel State across postbacks.

by Jon 7. April 2011 22:11

In 06?/07 the AjaxControlToolkit was the Jewel in the Crown in the Microsoft Web Development Platform , an easy way to do Ajax for Asp.Net Web Forms.  It was really easy rapid development, tightly integrated into Visual Studio and it was Open Source, it was new and cool and quick to use.  Things changed, the cool kids moved onto other things, and people discovered that although it had its advantages the AjaxControlToolkit to wasted lots of bandwidth, constricted you to a particular look and feel, and had the potential to introduce bugs you couldn’t fix.  The current state of play is the toolkit hasn’t seen a new release since September 2009, and frameworks and browsers progressed massively.

There are lot of sites and systems that still use ASP.Net WebForms and many of them use the AjaxControlTookit to fill UI gaps.  We still use this toolkit in our day job system and I decided that we need to swap out the functionality the toolkit provides to jQuery.  The two controls I needed to replace were the Collapsible Panel and the Accordion.  There were examples online on doing both but I couldn’t find any examples that persisted postback.  I needed a collapsible panel that I can expand and contract with AJAX/JQuery but when the user presses a button that posts back to the server I want the server to return the page in the same state before the postback, i.e. still expanded, or still collapsed.  I also need jQuery/a Pattern that can easily be swapped out and to keep the UI experience consistent so I can update multiple pages and controls in one refactor sweep.

Surviving Postback: Collapsible Panel , using jQuery

The following snippet of code is a drop in replacement for the AjaxControlToolkit Collapsible Panel, it has been written to be a simple replacement for he AJAX extender but using jQuery and a small amount of code behind to return the panel in the correct state on postback.  This is what you need to do if you want to create the sample in Asp.Net Webforms from scratch on a separate page but it is even easier to replace and customise all your collapsible panels in your existing application.

Include jQuery in your Page Header

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>

Add a Hidden Field to your Page/Control to store the Expanded State

<asp:HiddenField ID="ExpandState" runat="server" />

There is a Panel that shows some header information

<asp:Panel ID="Panel_Title" runat="server" Height="15px">
    <asp:Label ID="Label_Expander" runat="server" style="float: left" Text="Edit (Show...)" />
    <asp:Image ID="Image_Expander" runat="server" ImageUrl="/images/dn.gif" style="float: right" />


There is a Panel that shows some content

<asp:Panel ID="Panel_Content" runat="server" style="overflow:hidden">
    This is some Content

Add some jQuery to Expand and Contract the Content Panel when a user clicks on the Title Panel

<script type="text/javascript">
    $(document).ready(function () {

        // When a user clicks on the Title Panel
        $("#<%= Panel_Title.ClientID%>").click(function () {

            // Toggle the Panel_Content Visibility
            $("#<%= Panel_Content.ClientID%>").slideToggle(300, function () {

                // When the Content Panel has completed its animation check to see if the Content Panel is visible
                if ($("#<%= Panel_Content.ClientID%>").is(":visible")) {

                    // Set the HiddenValue Expanded State to 'Expanded' and Update the UI
                    $("#<%= ExpandState.ClientID %>").val("Expanded");
                    $("#<%= Label_Expander.ClientID %>").html("Edit (Hide...)");
                    $("#<%= Image_Expander.ClientID %>").attr("src", "/images/up.gif");

                } else {

                    // Reset the Hidden Value and reset UI back to its original State
                    $("#<%= ExpandState.ClientID %>").val("");
                    $("#<%= Label_Expander.ClientID %>").html("Edit (Show...)");
                    $("#<%= Image_Expander.ClientID %>").attr("src", "/images/dn.gif");






In your code behind add this code in the page/control load:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ' Serverside Expander Code
    If Me.ExpandState.Value = "Expanded" Then
        Label_Expander.Text = "Edit (Hide...)"
        Image_Expander.ImageUrl = "/images/up.gif"
        Label_Expander.Text = "Edit (Show...)"
        Image_Expander.ImageUrl = "/images/dn.gif"
        Panel_Content.Style.Add("display", "none")
    End If
End Sub

Surviving Postback: AjaxControlToolkit Accordion, using jQuery

The following snippet of code is a drop in replacement for the AjaxControlToolkit Accordion, you can simply replace the AJAX extender with the jQuery and add a small amount of code behind always show the correct panel on postback.  This accordion only shows one panel at a time. This is what you need to do if you want to create the sample in Asp.Net Webforms from scratch but it was written so it is really simple to swap out your old Accordions.

Include jQuery in your Page Header

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>


Add a Hidden Field to your Page/Control to store the clientid of the currently Expanded Panel.  The value of this hidden field is “” when there is no expanded panel

<asp:HiddenField ID="ExpandedClientID" runat="server" />


Any Number of Title and Content Panels

<asp:Panel class="TitlePanel" ID="Panel_Title1" runat="server" Height="15px">
    <asp:Label ID="Label_Expander1" runat="server" style="float: left" Text="Title 1" />
<asp:Panel runat="server" ID="Panel_Content1" class="ContentPanel">
    Content 1
<asp:Panel class="TitlePanel" ID="Panel_Title2" runat="server" Height="15px">
    <asp:Label ID="Label_Expander2" runat="server" style="float: left" Text="Title 2" />
<asp:Panel runat="server" ID="Panel_Content2" class="ContentPanel">
    Content 2


Add the following jQuery code

<script type="text/javascript">
    $(document).ready(function () {

        //toggle the component with class ContentPanel when the corresponding Title is clicked
        $(".TitlePanel").click(function () {

            // The Content Panel we want to manipulate is the Next One after this
            var ThisNextContentPanel = $(this).next(".ContentPanel");

            // Toggle This Content Panel
            ThisNextContentPanel.slideToggle(300, function () {

                // and then Hide the Other Content Panels

                // Set the Selected Panel to the Hidden Variable
                $("#<%= ExpandedClientID.ClientID %>").val(ThisNextContentPanel.attr('id'));





Add the follow code behind to make sure we only display the correct panel on each postback:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Show/Hide Panel_Content1
    If Panel_Content1.ClientID = ExpandedClientID.Value Then
        Panel_Content1.Style.Add("display", "none")
    End If

    ' Show/Hide Panel_Content2
    If Panel_Content2.ClientID = ExpandedClientID.Value Then
        Panel_Content2.Style.Add("display", "none")
    End If
End Sub


And that's it, we are now several steps closer to dropping the AjaxControlToolkit from our code base Smile

Tags: , , , ,

AjaxControlToolkit | vs2010 | jQuery


Getting Started with Continuous Integration with TeamCity in under 5 minutes!

by Jon 31. August 2010 22:17

Continuous integration is a way of increasing your productivity by automating the repetitive tasks you perform each day and as a function will improve the quality of the code you check into your source control system. It will give you more free time to develop better code, and will help you constantly improve yourself. If you find yourself doing the same thing day after day as a developer you really start automating those steps.

The good thing is it is really easy to setup a Continuous Integration. Within 5 minutes you could have installed and configured a system that will automatically compiled your code on a server when you perform a check-in and have any problems automatically reported back to you! What are you waiting for:

Make sure you choose a free TCP Port
Make sure you choose a free TCP port

Confirm the url for the Team City Installation has the correct port
Confirm the url for the Team City Installation has the correct port

Start the Services, and start TeamCity
Start the Services, and start TeamCity

Team City Starts
Team City Start

Accept the licence
Accept the licence

Enter an administrators details
Enter an administrators details

Team City is Started, and is prompting you to create a project
Team City is Started

Enter a project name
Enter a project name

Create a Build Configuration Called Build
Create a Build Configuration Called Build

Enter your SVN Settings for the project
Enter your SVN Settings for the project

Test the SVN Connection
Test the SVN Connection

Choose VisualStudio (2005/2008 or 2010) as a Build Runner, and Enter the Solution you want to Build
Choose VisualStudio as a Build Runner, and Enter the Solution you want to Build

Confirm the solution Builds from the Projects Screen, and then edit the Build
Confirm the solution Builds from the Projects Screen, and then edit the Build

Set the build to be automatically triggered when you Commit changes to SVN
Set the build to be automatically triggered when you Commit changes to SVN

and that's it, your Continuous Integration Server is up and running. Every time you commit a code change to SVN your solution will be automatically compiled. The sky is the limit, you can move over to a MSBuild Build Runner, perform automated tests, Generate Documentation, Code Statistics, Build and Install Deployment Packages. I've only just started using CI/TeamCity in my day job but I plan to Blog about my experiences as I implement more features. So far I have moved the office Build over to msBuild, automated developer statistics and RSS feed, and automated deployment to our test server. So expect some Blog entries on this in the coming weeks...

Guathon 2010, London

by Jon 15. August 2010 01:57

Guathon is about to start

Four people chatting before the guathon starts...

Tags: , , , , , , ,

asp.net | Deploy | development | scottgu | vs2010 | WP7


Uk Techdays

by Jon 8. May 2010 20:34


Uk Techdays Visual Studio 2010 Launch

UkTechDays; was 5 day events developer events hosted by Microsoft at two cinemas in London.  Although the usual goodies were lacking everyone had a great time and I learnt lots especially in development areas that I don't normally come into contact with. Credit must still go out to Microsoft for organising a week of free training/lectures, the quality of the speakers was really excellent.  Unfortunately the free copy of visual studio that delegates received at the both the vs2005 and vs2008 launches wasn’t repeated at the vs2008 launch in London.  But on balance what is most important is about keeping up-to date with the latest changes to the framework and development practices.

If you missed the event, or just want to catch up Microsoft has now made all the videos available here.

I attended the first two days, and took notes until I either got too excited or lost interest, this blog post is a regurgitation of these notes.  As I wasn't able to attend all week due to work and costs, these notes only cover the first two days.

Monday 12th April 2010 – First Day

I arrived in London the night before, and got to the Vue Cinema in plenty of time to get a coffee and get a good seat.

UkTechDays Introduction

Windows Development with Visual Studio 2010 - Matt Nunn, Senior Product Manager, Visual Studio

This session covered lots of new features that developers will benefit from in visual studio 2010

  • Partial String Intellisence - Intellisence has been improved, filtering now works with substrings or the Capitalised letters.
  • Multi Monitor - Windows can be broken off the Visual Studio Development Enviroment, and they can be moved to a separate monitor and docked there instead.  I think this will be great if you have 3 monitors but less useful for laptop based developers.
  • Zooming - Visual Studio 2010 has been rewritten in WPF so zooming is soother and the interface is slicker.
  • Test Driven Development Support – Useful if you have ultimate version of Visual Studio.
  • Extension Manager - Visual Studio extensions are now controlled from a funky new extension manager which appears to work more like a store where you can try, buy and remove extensions and features as you see fit.
  • JQuery - I haven’t used jQuery myself but I know a few people do.  jQuery is now properly supported in vs2010 and Microsoft is collaborating into the Open Source Project.
  • Lean Code Only - Some developer love code so much they don’t care about UIs.  Well Microsoft has now given us a way to develop in a code only view which hides away all the UI stuff. Great if you are writing drivers, or you are a proper geek.

Over the years C++ has been left behind in the visual studio world.  Vs2010 brings C++ upto date.  There was a fantastic demo on an old MFC application and how you can add windows 7 features really easily with visual studio 2010.  If you are a C++ developer VS2010 is defiantly an upgrade you should be looking at.  You get the class wizard back again, and you can do touch screen integration and everything else you would expect to see in windows 7.

Share point was also covered briefly; sharepoint development is much much easier in VS2010, but I think SharePoint is still too expensive for most developers to even consider so I won’t write anything else about it.

Web and Cloud Development in vs2010 - Richard Erwin, Technical Specialist, Developer & Platform Evangelism, Microsoft

There were a couple of demos, but I picked up the following nuggets on windows 7 phone:

  • UI Development for windows phone is vertical the XAML is shown side by side to the WUSIWYG editor.
  • Windows phone emulator is also hardware accelerated on the windows desktop (which is coo and needed because the windows 7 phone has 4 cores!)
  • Windows phone 7 is out later this year, sometime before Christmas

SharePoint and Office Development with Visual Studio 2010 - David Bishop, Principal Program Manager Lead, Developer & Platform Evangelism, Microsoft

I enjoyed this session, I get SharePoint but it’s not an area I work in and I don’t see the point for most developers due to cost constraints so I'm not going to write up my notes. Lots of developers started walking out at this stage, and there were lots of tweets from unhappy devs. However I thought it was a good session, and SharePoint may be something we want to get into later, especially if the cost is made less prohibitive.  If you do SharePoint development or your interested I recommend watching this video on the uktechdays website.

Improving Developer-Tester Collaboration with Visual Studio 2010 - Giles Davies, Technical Specialist, Developer & Platform Evangelism, Microsoft

Again it all looks great, but most developers can’t afford Ultimate Edition and lots of developers switched off. It is a shame as it is all good stuff but unfortunately we won’t get to use all these lovely features.

Unveiling the new and useful features of .NET Framework 4 and Visual Studio 2010 - Giles Davies; Richard Erwin; Mike Taulty; Eric Nelson; Mike Ormond; Mark Bloodworth

Ohh this was very meaty, it was split over two sessions reaching out until lunch because there were so many demos and so much information I’m just going to give brief bullet points.

  • Implicit Line continuation – No need to have those nasty underscores
  • C++ has a new dynamic keyword
  • Com Interops are better, comtypes are embedded in dotnet, ie a comtype library is no longer needed.
  • Web.Config and other config files have been imporved, we have different config files for different deployments.
  • Performance monitoring features, allows you to see what is going on in more detail it is a nice graphic display of how your code works. I think this is going to be fantastic for deep analysis of services running on multi core machines.
  • Caching in Asp.net is much more efficient
  • Session state can now be compressed
  • There is a new code block <%: which will automatically html encode
  • Webforms can now generate pure CSS friendly XHTML strick
  • Support for ASP.net MVC
  • Webforms isn’t going to be dropped, but It is clear MVC is going to be the recommended technology for web development.

Mike Taulty then took over and did a load of demos, RIA Services look fantastic, and defiantly something I want to look into in future

  • Visual Studio loves XAML based applications
  • XAML apps are made really simple if you want, you can write a Silverlight app without writing a single line of code if you want.
  • XAML is like windows forms point and click development, if you want it to be

Some other nuggets from the morning sessions

  • Entitiy framework 4 is a leap forwards as it fixes problems people experienced in older versions
  • Support for foreign keys on objects in EF4
  • You can take a group of properties and easily convert them into a complex type in the editor
  • If you use a stored procedure it will automatically create a matching complex type that works, which is a sensible outcome
  • Lazy Loading is on by default
  • POCO looks cool, but it isn’t in the initial release of vs2010, it is a code only interface to a database
  • In POCO you create a pure class, populate a few with data and save them to the database without writing ther database code
  • Parallel.Invoke will automatically split work across multiple cores efficiently

A Perspective on Agile Development - Colin Bird, Founder, Ripple Rock

It was a good session but you got the feeling Colin was trying to sell his services over demonstrating Agile best practices. I know I am not agile yet, but I intend to get there by continuously improving myself and our business practices. I am not going to big bang to agile I am going to get there in small steps. There were some great bullet points from this session:

  • Everything should be production ready all of the time
  • Agile is binary, it is either completed or not
  • Don’t commit part of the solution
  • Limit your work to what you have started and only do one thing at a time
  • Don’t Create a technical Debt
  • Lots of refactoring is needed all of the time
  • You need unit tests, performance tests regression tests
  • You need lots of interaction between people
  • Your aiming for Every bit of work you commit to be a mini waterfall. Analyse the problem, Design, Develop, Deploy and Test EACH time you commit changes
  • Look at implementing continuous integration
  • Agile is reactive to change
  • Encourage change and feedback from customers
  • Automate as much as possible, especially deployment try and deploy as much as possible

Fun Programming with Visual Studio - Rob Miles, Academic from University of Hull, Microsoft MVP

This was by far the best session of the two days. I am defiantly having a go at writing a game. XNA is a fantastic way into software development and it is something they should be teaching in schools across the country. Rob impressed the audience and showed us it is really simple to make a game that you can deploy to an xbox360, windows 7 phone or run on your home pc. His new book looks like it will be fantastic for beginners.

Tags: , , , ,

asp.net | conference | General | vs2010


It is Saturday evening and I have almost recovered from my Scott Guthrie induced migraine

by Jon 27. March 2010 23:39

Scott Guthrie

I think I have almost recovered and I can finally put some of the stuff I saw and learnt down on screen.  I have had my migraine since around 2pm yesterday, pain killers couldn’t hold it back.  It’s hardly a surprise as it was initiated by Scott Guthrie filling my brain with too much dotnet goodness. Who is this Scott Guthrie bloke anyway and how did all this all happen, and why don't I mind that much? 

Scott is a software developer, he wears a red polo shirt, but more importantly co wrote (yes wrote!), asp.net!  He was a founding member of .net itself and he is official title is ‘Corporate vice president of Microsoft's .NET Developer Platform’.  If you want to hear about dot net he is the bloke to listen to.  Scott was in the UK for two days to give two five hour sessions three of the projects that under his wings:

  • Visual Studio 2010 and asp.net 4
  • Asp.net Model View Controller (MVC)
  • Silverlight and Windows Phone 7 development

I went to the second Guathon which was held in Birmingham City Centre Odeon cinema yesterday.  It was an all day event; Scott did a mammoth five hour talk with only a couple of short breaks for a bite to eat or to grab a bottle of water.

Visual Studio 2010 and Asp.net 4

In the morning session Scott started by going over all the great improvements to visual studio, in brief vs2010 is a big improvement on vs2008, its faster, its easier to see your code, you have more customisation, you can run multiple monitors more effectively and there are lots of refactoring features that make making writing and changing code much quicker.  In summary it is much better, it is a no brainer even if you are going to continue to develop in anything from dotnet 2 and above.  Scott deep dived into vs2010 to show these features, and also demoed lots of improvements to dotnet and asp.net and beyond.

Asp.net Model View Controller (MVC)

This was the second time I saw a session on MVC, but this time I got it. Scott explained asp.net MVC really clearly, its quite a jump from traditional asp.net but I can see the massive improvements it will bring. Although MVC development turns development on its head you can see how code reuse is much more effective and when combined with entity framework 2 it will makes for a very agile development process.

Silverlight and Windows Phone 7 Development

Another fantastic session, it made developing Silverlight look very simple there are big improvements in vs2010 to the development environment to support Silverlight developers and make it less daunting. Windows phone 7 looks like a real iPhone killer, the min specs are a quad core ARM processor combined with a GPU! Windows phone 7 apps are Silverlight so they are quick and smooth and ready to develop. A twitter Silverlight app was developed from scratch and deployed to a phone within 5 minutes live on stage, very impressive.

Odeon Cinima in Birmingham filling up with dotnet developers for the Guathon
Odeon Cinima in Birmingham filling up with dotnet developers for the Guathon

Head Honcho ScottGu from Microsoft about to start one of his presentation at the Guathon
Head Honcho ScottGu from Microsoft about to start one of his presentation at the Guathon

In summary it was a fantastic event, and amazing considering it was free! A big thanks must go to Phil Winstanley for arranging and organising it.

Powered by BlogEngine.NET
Original Design by Laptop Geek, Adapted by onesoft, and finally some tiny tweaks by JonAlb