Retain position of a DragPanel Extender after postback using ASP.NET AJAX

Posted by: Suprotim Agarwal , on 7/29/2008, in Category ASP.NET AJAX
Views: 97042
Abstract: The DragPanel extender makes it extremely simple to add a ‘drag’ to your controls. However there is a functionality missing in the DragPanel extender. The DragPanel extender does not have the built-in capability to retain the position of controls that have been dragged, after a page postback. In this article, we will see how to retain the position of the DragPanel extender, after a postback.
Retain position of a DragPanel Extender after postback using ASP.NET AJAX
 
The DragPanel extender makes it extremely simple to add a ‘drag’ to your controls. It can target any panel control which enables you to move your panel from one place to another, on the client-side. However there is a functionality missing in the DragPanel extender. The DragPanel extender does not have the built-in capability to retain the position of controls that have been dragged, after a page postback. In this article, we will see how to retain the position of the DragPanel extender, after a postback. This tip was shared by Jonathan in the asp.net forums. I will be building up on that trick and show you a step by step process on how to do it.
I assume you have some basic experience developing ASP.NET Ajax applications and have installed the ASP.NET Ajax Library and ASP.NET Control Toolkit. As of this writing, the toolkit version is Version 1.0.20229 (if you are targeting Framework 2.0, ASP.NET AJAX 1.0 and Visual Studio 2005) and Version 3.0.20229 (if targeting .NET Framework 3.5 and Visual Studio 2008).
This article has been created using Version 3.0.20229 (targeting .NET Framework 3.5 and Visual Studio 2008).
Step 1: Open Visual Studio > File > New Web Site > ASP.NET Web Site > Choose the location and language and click OK.
Step 2: Drag and drop a <asp:ScriptManager> control to the form. Also add a <div> to the page with the following properties:
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <div>   
            <div style="height: 300px; width: 250px; padding: 20px;">
 
            </div>       
        </div>   
 
    </form>
   
</body>
Step 3: Now inside the <div> add a Panel Control called “Panel1”. Inside this <Panel>, add another panel called “Panel2”. We will be dragging Panel1 across the screen. After setting properties on the <Panel>, the code would look similar to the following.
        <div>   
            <div style="height: 300px; width: 250px; float: left; padding: 5px;">
                <asp:Panel ID="Panel1" runat="server" Width="250px">
                     <asp:Panel ID="Panel2" runat="server" Width="40%" Height="20%" BorderWidth="1px" BorderStyle="Solid"
                        BorderColor="black">
                            Drag This Panel
                    </asp:Panel>    
                </asp:Panel>
            </div>       
        </div>
Step 4: Now add a DragPanel Extender from the Ajax Control Toolkit in the toolbox, to the page. Set its TargetControlID and DragHandleID to ‘Panel1’. Also set its BehaviorID to ‘DragP1’
        <cc1:DragPanelExtender ID="Panel1_DragPanelExtender" BehaviorID="DragP1" runat="server"
            DragHandleID="Panel1" Enabled="True" TargetControlID="Panel1">
        </cc1:DragPanelExtender>
Also add a button control to the page and now run the application. Drag the panel and place it at a different position. Now hit the button. You will see that a postback occured and that the Panel position was reset to its original position.
Step 5: We will now add some script to maintain the position of the panel after postback. We will be adding a HiddenField which will store the position of the dragged panel. The value has been initially set to “0”.
<asp:HiddenField ID="HiddenField1" runat="server" Value="0" />
When the panel is dragged, the value is temporarily stored in the hidden field. When the page is posted back, in the pageLoad(), we will retrieve the value from the hidden field and manually set the position of the panel.
Here’s the script to do so:
<script type="text/javascript" language="javascript">         
 
function pageLoad()
{  
    // call the savePanelPosition when the panel is moved
    $find('DragP1').add_move(savePanelPosition);  
    var elem = $get("<%=HiddenField1.ClientID%>");   
    if(elem.value != "0")
    {
        var temp = new Array();
        temp = elem.value.split(';');
        // set the position of the panel manually with the retrieve value
        $find('<%=Panel1_DragPanelExtender.BehaviorID%>').set_location(new Sys.UI.Point(parseInt(temp[0]),parseInt(temp[1])));
    }
}        
 
function savePanelPosition()
{
    var elem = $find('DragP1').get_element();
    var loc = $common.getLocation(elem);
    var elem1 = $get("<%=HiddenField1.ClientID%>");
    // store the value in the hidden field
    elem1.value = loc.x + ';' + loc.y;
}
          
</script>
The savePanelPosition() gets the location of the Panel. The savePanelPosition() gets called every time the panel is dragged. This is possible as in the pageLoad(), we have registered add_move() on the Panel and set it to call the savePanelPosition() method. In this method, we then store the location of the panel in the HiddenField. The loc.x and loc.y represent the x and y co-ordinates of the dragged panel, which is stored as a semicolon(;) delimited string.
When the page is posted back, we retrieve the value of the HiddenField in the pageLoad() function. If the value is not “0”, we retrieve the value in an Array (by splitting the semicolon delimited string) and then set the position of the Panel manually using the retrieved value.
You can now run the application, drag the panel and hit the button. If you have followed the steps correctly, you will observe that the panel retains its position, after a postback. The entire source code will look similar to the following:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
 
<!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 id="Head1" runat="server">
    <title>Retain Postback</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <div>   
            <div style="height: 300px; width: 250px; padding: 5px;">
                <asp:Panel ID="Panel1" runat="server" Width="250px">
                     <asp:Panel ID="Panel2" runat="server" Width="40%" Height="20%" BorderWidth="1px" BorderStyle="Solid"
                        BorderColor="black">
                            Drag This Panel
                    </asp:Panel>    
                </asp:Panel>
            </div>       
        </div>
   
        <cc1:DragPanelExtender ID="Panel1_DragPanelExtender" BehaviorID="DragP1" runat="server"
            DragHandleID="Panel1" Enabled="True" TargetControlID="Panel1">
        </cc1:DragPanelExtender>
        <script type="text/javascript" language="javascript">         
 
                function pageLoad()
                {  
                    // call the savePanelPosition when the panel is moved
                    $find('DragP1').add_move(savePanelPosition);  
                    var elem = $get("<%=HiddenField1.ClientID%>");   
                    if(elem.value != "0")
                    {
                        var temp = new Array();
                        temp = elem.value.split(';');
                        // set the position of the panel manually with the retrieve value
                        $find('<%=Panel1_DragPanelExtender.BehaviorID%>').set_location(new Sys.UI.Point(parseInt(temp[0]),parseInt(temp[1])));
                    }
                }        
 
                function savePanelPosition()
                {
                    var elem = $find('DragP1').get_element();
                    var loc = $common.getLocation(elem);
                    var elem1 = $get("<%=HiddenField1.ClientID%>");
                    // store the value in the hidden field
                    elem1.value = loc.x + ';' + loc.y;
                }
                  
        </script>
       
    <asp:Button ID="Button1" runat="server" Text="Button"/>
    <asp:HiddenField ID="HiddenField1" runat="server" Value="0" />
    </form>
   
</body>
</html>
 
I hope you liked the article and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed. 
 
 
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Ajax Learner on Friday, August 15, 2008 1:58 PM
Hey, You did really well!!
Thanks for sharing...
Comment posted by Santosh Kumar on Friday, August 22, 2008 2:10 AM
thanks,
this is realy good work done , but it only available running browser not always store.

http://www.operativesystems.com
Comment posted by janx on Wednesday, September 24, 2008 11:56 AM
Hello,

How are you to do this if the Panel and Button are both inside a repeater. Thanx.
Comment posted by Thanigainathan.S on Tuesday, November 25, 2008 12:53 PM
Hi,

This is really nice tutorial. Thanks for the info . Is the drag panel only available for panel controls or some other controls also ?

Thanks,
Thani
Comment posted by Don on Tuesday, November 25, 2008 3:44 PM
<i>but it only available running browser not always store</i>

You could either save the coordinates to the cookies collection or to the database and then retrieve it on page load in order to get this to work even after the browser is closed.
Comment posted by Suprotim Agarwal on Tuesday, November 25, 2008 9:35 PM
Thanigainathan: The DragPanel is for panel controls.

Don: Thanks for the tip.
Comment posted by Kaushal Anand on Tuesday, March 3, 2009 3:01 AM
i getting error with mozilla. The $find('DragP1').add_move(savePanelPosition) is not working with mozilla. I think its not being called by Firfox.
Please help me...
Comment posted by Dave Conner on Wednesday, April 8, 2009 5:50 PM
Thanks for the clever trick... worked fine for me with IE6 and IE7.

I placed gridview in the panel, and position was retained...
Comment posted by TonyO on Tuesday, August 4, 2009 10:11 AM
Hangs if you maximise the screen
Comment posted by Bjørn Gustafson on Monday, November 2, 2009 3:56 PM
A very useful post, but I'm having some trouble with the implementation when UpdatePanels are involved.
I have successfully added you script to my modal popup, and it does indeed retain its position across postbacks.
However, the panel being dragged contains an update panel with controls that perform postbacks.
In my dummy sample, I have an updatepanel with a button and a label, and when the button is clicked, the foreground color of the label is toggled between red and black.
This works perfectly without your javascript.
However, as soon as I add the script, although the position is being retained, the postbacks does not occurr as expected.
Postbacks ARE indeed triggered, as I catch them in code behind, but there's something funny going on with the order of the events.
In my sample, the text turns red, but is never again turned black. The state of the controls seem messed up, and events which shouldn't have been fired seem to fire as well.

Have you tried your code with an UpdatePanel inside your draggable panel?
If not, why don't you give it a try and see if you can replicate the problem.
The solution seems very close, but I'm not experienced enough with AJAX and javascript to see what's going on here.

If you are able to replicate the problem, and find a fix for it, i'd love it if you dropped me an email!
Thanx,
-b
Comment posted by Ravinder on Thursday, March 4, 2010 2:21 AM
A very useful post, but I'm having some trouble with the implementation when UpdatePanels are involved.
I have successfully added you script to my modal popup, and it does indeed retain its position across postbacks.
However, the panel being dragged contains an update panel with controls that perform postbacks.
In my dummy sample, I have an updatepanel with a button and a label, and when the button is clicked, the foreground color of the label is toggled between red and black.
This works perfectly without your javascript.
However, as soon as I add the script, although the position is being retained, the postbacks does not occurr as expected.
Postbacks ARE indeed triggered, as I catch them in code behind, but there's something funny going on with the order of the events.
In my sample, the text turns red, but is never again turned black. The state of the controls seem messed up, and events which shouldn't have been fired seem to fire as well.

Have you tried your code with an UpdatePanel inside your draggable panel?
If not, why don't you give it a try and see if you can replicate the problem.
The solution seems very close, but I'm not experienced enough with AJAX and javascript to see what's going on here.

If you are able to replicate the problem, and find a fix for it, i'd love it if you dropped me an email!
Thanx,
-b
Comment posted by Reddy on Friday, March 5, 2010 10:25 AM
Please help me how can i use the same concept for 2 drag panels and want to save the positions of 2 drag panels.
Please send me the solution to patelravinderreddy@gmil.com .
waiting for reply
Thanks In Advance .........
Comment posted by Manisha on Thursday, April 15, 2010 11:04 AM
Hi,

it's realy a nice article. I have one question. can you tell me how to do this for multiple DragPanelExtender

Thanks!
Comment posted by Sudipta on Friday, May 7, 2010 12:21 PM
Thanks... its help me lot.
Comment posted by Vanitha on Friday, September 17, 2010 4:58 PM
How to retain position of dynamically created DragPanel extender[more than 3] ?
Comment posted by Udhay on Wednesday, December 15, 2010 1:29 AM
I tried this for my project, but i am facing some trouble if i have vertical or horizontal scroll bars. its going to the same location, if drag it. i am showing an image in a web page and i need to allow my user to comment on any location. So i am showing a dragpanel with textbox control. if the picture is big in size the i am scroll bars. in that case its not moving. can u plz help me on this???
Comment posted by vishal on Thursday, March 10, 2011 5:25 AM
not working this by using toolkit manager
Comment posted by Manoj Bhatt on Monday, January 2, 2012 5:12 AM
Hi,

I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of Ajax Toolkit DragPanelExtender Control in ASP.Net and it will help me a lot.
Thank for sharing with us. Please check out this helpful link too its also having nice post with wonderful explanation on Ajax Toolkit DragPanelExtender Control in ASP.Net.....
http://mindstick.com/Articles/505e257a-7411-45b6-9ab9-65dfcf84edf6/?Ajax%20Toolkit%20DragPanelExtender%20Control%20in%20ASP.Net

Thank you very much!
Comment posted by Muthupandian on Sunday, March 31, 2013 2:24 AM
How to create more than one drag panel using same drag handle id
Comment posted by AIzhong on Monday, March 24, 2014 5:12 AM
this is awesome and clear instructions .

do u know a way to restrict the dragging area? or does ur ebook provide such solutions?

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook