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


Deploying Asp.Net to a different time zone, Temporal Future Shock! Specified argument was out of the range of valid values. Parameter name: utcDate

by Jon 17. December 2010 09:57

You would have never of thought it but if you compile ASP.NET in a different timezone you could cause yourself some temporal problems.  I recently discovered that parts of ASP.NET are date specific and if you compile an ASP.NET application in one timezone (The UK), and deploy to another timezone (California) you may find that your web application won’t work correctly until the time catches up.  Its all to do with the date stamp in the assemblies, when you install your application onto a server in california the timestamps on the assembly files may be in the future and parts of the ASP.NET framework will refuse to load them.  Just by waiting 8 hours for time to catch up the problem will resolve itself!  Its defiantly worth saying this doesn’t effect all server setups I had no problems with a customer running server 2008 in a different timezone, I only came across this problem with an AJAX enabled system when a customer was running server 2003, but I haven’t had time to test different scenarios

I installed the application the AJAX was ‘working’ however nothing was styling correctly

I viewed the source of the page and started debugging by copying the WebResource.xsd url into different tab, I was surprised to see the following error:

Server Error in '/' Application.

Specified argument was out of the range of valid values.
Parameter name: utcDate

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: utcDate
Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

I returned to the system after 8 hours and the site was working and the error was gone! Be careful out there, this was a fully patched server 2003!

Tags: , , , , , , ,

asp.net | Deploy | development | General | IIS | Maintanance | TechSupport | vs2010


Developer Developer Developer 8a 23rd Oct 2010; Another great community day by the DDD team

by Jon 23. October 2010 18:59

I’m heading home after another long but fantastic day at Microsoft Reading, UK.  The day officially started started at 8am with bacon butties laid on by the venue hosts Microsoft who provided an excellent venue for this Mini Geekathon at there UK offices in Reading.  However that is pretty much where Microsoft's roles ends and the community takes over.  Developer Developer Developer is a group of individuals that get sponsorship and lay on development events around the UK.  The DDD events are FREE events organised by developers for developers; todays event was titled Modern.Net.  Modern.Net is .NET we can do now with current tools the idea of the day was to cover all the latest things in .NET that developers can use now to target Acer Aspire One, Amazing Battery Lifenew platforms and write better code.  I came armed with my new mini Acer aspire one, which appears to have better battery life than I expected.  I was surprised to see 8hours 46 mins remaining after a couple of hours of use on the way down and that's with Bluetooth turned on and active!

The day was split Into two rooms which made it really difficult to choose sessions to attend as I would have loved to see the sessions that were running in the room next door.  I resolved this problem by pretty much deciding which session to attend at the last minute.

WP7, iPhone, Droid - Oh My ! - Chris Hardy

Did you know you could develop against the three most important smart phone device types just with.NET?  Chris went through the different ways you develop each platform, explaining the differences and requirements for each smartphone.

Phone Platform Cost My Notes
Windows Phone7 Windows,
Visual Studio
vs2010 Express $0
Appstore $99 PA
Nice and simple develop, as it is just Silverlight.  It has some oddities due to Tombstoning but this should be the easiest and cheapest platform for .NET developers to get into.
iPhone Mac, Mono Develop, Mono Touch Monotouch $400, Appstore $99 PA You need a Mac to develop this because you need to have the IPhone SDK that only works on a Mac.  There are lots of restrictions and tricks (ahead of time compiler, stripping out bits of the framework you don’t need at compile time) that have been performed by the MonoTouch developers to get this to work which means you will always be lumbered with a larger assemblies.  However the advantages of using MonoTouch over Objective C is Clear and it now sounds like Apple has now embraced MonoTouch as an easier way of developing for there platform.
Android Mac/Windows/Linux, Mono Develop, Mono Droid MonoDroid $1000
Appstore $25 One Off
Although MonoDroid is at an early stage it looks the most exciting to me; apart from the high cost of the Licence for MonoDroid.  You can develop MonoDroid from any platform, and although there is the odd fudge it looks like it will be a much better development experience for developers when the product is released.  You can create widgets and applications with MonoDroid, and you can get access to other libraries such as OpenGL.  There are currently a couple of issues including asynchronous and multi Threading not working yet but they will be fixed when MonoDroid is released.


Chris Scaring us with MonoTouch Minimum App SizeWP7 is clearly the easiest platform to develop for in .Net but the advantages of .Net for the other smartphones is clear.  Developers are now able to separate logic and develop a re-useable libraries that if developed carefully can be reused between the platforms thus reducing the pain of developing cross platform smartphone applications .  Most Interestingly I personally think that the relatively low cost and ease of development bodes very well for the new WP7 platform.

Managed Extensibility Framework - Kathleen Dollard

This was my favourite session of the day; i had heard bits and bobs about MEF from other developers prior to this session but I haven't had time to investigate it so I was looking forwards to this session by Kathleen.  Kathleen enthusiastically explained MEF from the basics to the detail by rattling through two presentations in the limited time at breakneck speed.  I didn’t get it all and the certainly wasn’t time for detailed notes but here are the basics.

MEF is different, stands for Managed Extensibility Framework and developers can used it to develop separate units that can work together but so the logic can separated more sensibly.  Imagine a room of kids drawing things, some have crayons some don’t, some kids are shouting I want a crayon, other kids are shouting I want a crayon.  MEF is the system that can be used connect the kids who want crayons to people who have crayons.  There are currently two models available to do this, one of the models is designed especially for Silverlight, the other is more general purpose for dotnet.

One thing I found interesting is that essentially it is DIY SOA, if you want a flexible SOA architecture this seems like a great way to go.  Kathleen gave lots of examples why MEF or something like it is the future.  Although I haven’t explained it very well it looks like a much much better way of developing systems, I defiantly need to see more sessions on MEF as I want to use it for some personal projects.

Dynamic Consumption in C# 4.0 - Oliver Sturm

I had seen Oliver Sturm before when he took us through f'# one evening after UkTechdays, gosh he is a clever bloke.  In this session Oliver took us through dynamic consumption and some of the dynamic features in c# 4.0.  As far as I can tell a chunk of the dynamic features in c# 4.0 have originated from vb.net so some of the ohhs and ahhs are less impressive to me as I have been using them for years and years in vb.net, c# has essentially caught up with vb.net, and has a few new dynamic features.  After demonstrating the dynamic features of c# he demonstrated how you can call dynamic languages from within c#, first doing office automation, and next calling out to python using a python library and returning the results into c# looks interesting if you need that kind of thing.  The summary c# isn’t dynamic but it can now interact with dynamic languages.  Useful to know if I ever need to do it, but at the moment its not something I will be doing.  IMO Vb.net developers will be less impressed with this presentation, but it was an interesting one to go to.

Lunch and Grok Talks

Jon Skeet wowing the audianceLunch was kindly provided by Microsoft and we sat in the main lecture hall munching away listening to some concise talks on a variety of subjects.  I liked the concept of a 20:20 presentation, 20 PowerPoint slides in set to auto run at 20 seconds for each slide, the presentation was on @plip and twitter but i liked the concept.  The talk on Behaviour Driven Design (BDD) was interesting, the presenter showcased his own framework for F'# called TickSpec.  I can see how his framework methodology has its benefits for highly specified systems.  Finally dinner ended in a geekout with different presenters from the day answering questions on .net and development theory from the audience, eye opening and I discovered an alterative (cooler?) way to say tuple!

Modern C#: This is not your grand-daddy's language - Jon Skeet


Jon Skeet pretty summed up the entire day with his presentation on modern C#.  The theme of the presentation was the theme of the day, Modern.Net and how it has evolved over the years by doing a direct comparison between the oldest and the newest version.  We can express more than we could before, C# 1 was wobbly wobbly, but today C# 4 is more descriptive and defined.


Jon lead us through the differences by deep diving into the code, he wrote the same code in both versions; find the maxby and return it and tried to make both solutions as defined and generic as possible.  The C# 1 code turned out to be simpler and shorter but the bug difference was in the reusability and strictness.  The C# 4 code was more reusable and strict at the same time, you had to jump through some nasty hoops to make the C# 1 code anywhere near as reusable and sensible.  At the end the C# was still shorter, but the client code required to use it had to be longer and there was defiantly a bigger chance to make an error with the C# 1 calling code.

At the end of an interesting talk, we were left everyone with a chunk of interesting thoughts…

  • f# is complicated but it has lots of inertia in the industry
  • Learn F# to improve your c# (and vb.net ;p)
  • Think about what is coming in future, dotnet 5

IMHO the future is more CPUs, so its worth bearing in mind when looking to the future.

WPF in Modern .NET - Ian Griffiths

Unfortunately I missed the start of this talk due to the start of a migraine, starting to feel very tired, and listening to Jon Skeet outside the hall for the first 15 mins of this session.  I stood at the back with @NathanGloyn and I took the opportunity to charge all mu devices, which stopped me from taking any notes.  Ian defended WPF throughout the session but in my mind didn’t really give much to backup his defence.  I’ve seen WPF before and yes it has its advantages and yes it will be used but I still don’t get the separation between Silverlight and WPF.  In my mind why separate the two it would be much better to have Silverlight, Silverlight, even if there are differences diluting two frameworks and having two brands doesn't seem the most sensible strategic decision.


And with that that was it, another long development day.  We all caught the bus back to the train station and scuttled off home on the train.  Thanks to all the organisers, and Microsoft for the venue, it was another fantastic day.  Hopefully one day I will complete a blog post on the day of a DDD event before a migraine stops me in my tracks!

Tags: , , , , , , , , , ,

conference | ddd | vs2010


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


Dotnet Gets it wrong sometimes: 'mycontrol_ascx' is ambiguous in the namespace '_ASP'

by Jon 7. June 2010 16:27

When compiling larger more complicated ASP.Net projects which contain lots of user controls dotnet can get it wrong.  Im running the latest version of vs2008 with all the last patches but I still get occasional niggles.  Ive been getting an error telling me a control is ambiguous when I know it is totally unique.  The solution appears to be to tell the compiler to stop being quite so clever:

Find this, or a similar line in your web.config:

<compilation debug="false" />

Modify it and add batch="false", this stops the compiler being too clever.

<compilation debug="false" batch="false" />

Tags: ,

asp.net | General | vs2010

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