Saturday, 7 June 2008

Ajax Web Parts Part 1 - Drag and Drop

Posts In This Series:

Introduction - ASP.NET AJAX and Web Parts
Ajax Web Parts Part 1 - Drag and Drop
Ajax Web Parts Part 2 - Web Part Connections
Ajax Web Parts Part 3 - Dynamic Web Parts
Ajax Web Parts Part 4 - Dynamic Web Part Connections


Download the source - Part 1
Download the source - Part 2
Download the source - Part 3
Download the source - Part 4



Introduction
In this post I'm going to describe the very basic steps required to get Web Parts drag and drop up and running from scratch. This will use a Calendar item, added to a Web Part Zone, to make a generic Web Part. This is the standard demonstration of Web Parts that has been used in a multitude of other Web Part tutorials - it's replication here is purely to get the basic components in place before moving on to other, more advanced, topics.

Click here to see what will be created.

Required Components
At present, due to the evolving nature of the subject, there are a large number of different versions of ASP.NET and its related components. These components can appear in releases with titles such as “futures”, “extensions” and “Community Technology Previews (CTPs)". As a result, one of the major challenges when working with ASP.NET is finding the appropriate set of components to use – each release appears to have its own unique fixes and quirks and, consequently, it can be difficult to find the correct combination to achieve the desired results. Hopefully ASP.NET 4.0 will fix all the bugs and tie everything together!

Therefore, when working with ASP.NET AJAX and Web Parts we will require more than the standard ASP.NET framework; extra components are needed either to add functionality or to fix problems in the current release. To begin with we will start with a standard system and add these extra components as required.

Initially, to follow along with the code in these posts, you will require 2 things:

1. Visual Studio 2008 or Visual Web Developer Express
2. The ASP.NET AJAX Control Toolkit





Creating the initial project
From the file menu, select "New Web Site" and then choose "AJAX Control Toolkit WebSite" from the list of available options:







Adding the Web Part Components
Now we need to add a few components to the page to give us something to work with.
From the toolbox, when in design or split mode, drag the following items onto the default.aspx page:
From the WebParts toolbox tab:


  • 1 x Web Part Manager
  • 2 x Web Part Zones

Then, from the Standard toolbox tab, drag a Calendar component and drop it into the first Web Part Zone - this will automatically convert the Calendar into a generic Web Part.

After the addition of these items, the default.aspx page should look as shown below (it also includes a ToolkitScriptManager which is there as a consequence of the initial project choice we made. At present this isn't being used, but will be required later.)


Before we can actually run this project, and get the drag and drop behaviour that we’re after, we need to make a small addition to the code behind.


Display Modes and Personalization
If you were to run the project in its current state, you would see one of two things - either you would get a database error, or you would see the Calendar component, but would be unable to change its position.

The reason why drag and drop is not yet possible is due to the display mode setting of the Web Part Manager. Display modes are used to define what operations can be performed on the Web Parts; the default display mode is "Browse" and this is the mode currently used by our page. In this mode it's only possible to do basic operations, such as minimize and close; it's not possible to perform drag and drop. To enable drag and drop requires, at a minimum, the display mode to be changed to "Display".

However, things aren't quite so simple. When web parts are moved on the page it's necessary to save the information about their new positions so that they can be restored to these locations the next time the page is rendered. This information is stored into a personalization table in a database. Thus, to enable the more advanced features of Web Parts, such as drag and drop, requires a database to be available. If you haven't yet got a database the easiest option is to download SQL Server Express.

To set the Web Part Manager’s display mode, add the following code into the Default.aspx.cs file:



protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// set the display mode to "Design" to allow drag and drop
WebPartDisplayMode mode = WebPartManager1.SupportedDisplayModes["Design"];
if (mode != null)
{
WebPartManager1.DisplayMode = mode;
}
}
}


If this is the first time that the page is being rendered (i.e. not a postback), then this code checks the Web Part Manager to see if the "Design" mode is contained in its list of supported display modes. If it is, then it sets this to be the current display mode.


We now have everything in place to enable drag and drop. Press F5 to run the project and hopefully you should see the following output:

If you have run this using Internet Explorer, drag and drop functionality should now be enabled:
- when the cursor is hovered over the title bar it should change to the directional cursor and clicking and holding on the Calendar web part's title bar should enable it to be selected and dragged to the second Web Part Zone.

However, with the current release of ASP.NET 3.5, if you have run this in a browser other than IE (e.g. Firefox), then the chances are that the drag and drop won't be working - to fix this we need to make another modification.


Web Part Drag and Drop in Firefox
For some reason Microsoft have chosen not to include the fix for Firefox (and other non-IE) browsers in the latest releases of the ASP.NET framework. To get things working in all browsers requires the download of the
Microsoft ASP.NET Futures (July 2007) Release - obviously this is a technology preview release and is therefore not supported for production sites - however, the alternative is to not have drag and drop support for all non-Microsoft browsers, so you need to choose which of these is the most important to you.

Once this futures release has been downloaded, its components need to be added to your Visual Studio toolbox. To do this, you need to do the following steps:

  1. In the toolbox window, move the cursor into the bottom tab pane and right click to bring up the context menu. From this choose "Add Tab" and create a new tab for the futures release.

  2. From within this new tab pane, select "Choose Items.." from the right-click context menu.

  3. In the dialog that appears choose browse and locate the futures DLL (mine was downloaded to C:\Program Files\Microsoft ASP.NET\ASP.NET Futures July 2007\v1.3.61025\3.5).Click on OK once all the components of this DLL have been selected. All these components should then be added to the new tab of the toolbox, as shown below.



As you can see, the toolbox now contains both a WebPartManager and WebPartZone that have been added from the Futures release. All we need to do now are replace the standard versions of these that we'd added already with these new Futures versions and that should fix our Web Parts drag and drop for all browsers.



AJAX Enabling The Web Parts
We've only one thing left to do, and that's remove the annoying postbacks that occur when the Web Parts are moved. To do this we simply need to wrap everything in an UpdatePanel from the AJAX Extensions tab of the toolbox. We already have a ScriptManager present from the AJAX Control Toolbox - however, for consistency, I've chosen to remove this and replace it with the standard version. Once everything is in place, the body of my default.aspx file now looks as follows:







Click here to see this in action.


This concludes the introduction to Web Parts. In future posts I'll expand apon this simple project to show how Web Parts can be combined with both the ASP.NET AJAX framework and the ASP.NET AJAX Toolkit Tab component.


25 comments:

Randall Flagg said...

That was a great tutorial, thanks! Do you still have plans to post a second part to this series (using AJAX Tookit Tab Component...)?

Steve said...

Hi Randall, I'm glad you liked the post. Due to other commitments there's been a bit of a delay in adding the rest of the posts in the series. However I'm just in the middle of putting the second part together now, so hopefully it should appear in the next week or so. Thanks again, Steve.

Aqil said...

The first tutorial that lead me to cross browser web part, but its making postback, hopefully in next tutorial you will mention that, plus using tabs and having adding webparts and tabs dynamically would be really great as you mentioned in your earlier post. Great work.

stealthboy said...

Following this example, I still do not have the drag and drop working properly in Firefox. It will allow me to drag the calendar only once, then after that I must reload the page if I want to drag and drop again. After the first drop, successive attempts give a javascript error about _whidbeyZone being undefined. Any ideas?

Aqil said...

"you currently can only drag and drop elements once, then the feature stops working. (If you refresh the browser, you can move the elements again—one time per browser refresh.) It is expected that future versions of the ASP.NET AJAX Futures release will provide a fix" ('Programming ASP.NET AJAX' by Christian Wenz)

But this problem was with previous versions, using VS2008, current release of ACT, Ajax future release solves this problem and its working fine now.

Steve said...

Hi Stealboy - sorry to hear it's not working for you - when you view the example from the post does this work?
Taking a rough guess it sounds like a versioning problem, which would point the finger at either the Microsoft.Web.Preview.dll or your ASP.NET version.
I've now made the source code available for download (check the links at the top of the post) - perhaps you could get this and see if it fixes the problem.

Steve

Steve said...

Stealthboy, is this the error that you're getting:
"Microsoft JScript runtime error: '_whidbeyZone.webPartTable' is null or not an object" ?

This error occurs if you don't put the WebPartManager inside the UpdatePanel where the WebPartZones are.

stealthboy said...

I have the manager inside the updatepanel.. the error I get is exactly this: "_whidbeyZone is undefined". It's a problem in the Javascript, specifically line 338 in the ScriptResource.axd file (WebPart.js) that is generated (handled by the ScriptManager, no?).

mart said...

Has anyone managed to get drag and drop working in firefox with 3.5 SP1?

For me it looks like the fix from the futures release wasnt included in SP1.

JeffCirceo said...

Nice article thought you might be interested in a project that I just started. TFRPortal the project has CSS friendly Web Parts with drag and drop. Take a look here

Steve D. said...

This was a great tutorial. I found it very helpful and you brought up several interesting concepts that open the door to new possibilities. Thanks for taking the time to share this information. I look forward to your future tutorials.

Unknown said...

If you get in trouble with web parts and FF 3.0.10, install IE8 and aspnet 3.5 sp1, then start your web part enabled web app in FF (for me via Visual Web Designer) and then left-click the FF logo (bottom right of browser): this switches to IE8 compatibility mode and enables correct display allowing drag-n-drop.

Unknown said...

I am adding wbpartzone and webpart dynamically through code(like in my.msn.com), In this case frist biggest problem is design, Zone not set properly in page. Control which is add in wepart also comes from database according, Which are previously saved by user
foreach (DataRow contdr in controldt.Rows)
{
string contr = contdr["ControlName"].ToString().Trim();
Control control = LoadControl("~/UserControl/" + contr);
control.ID = contr;
WebPart myWebPart = WebPartManager1.CreateWebPart(control);
WebPartZone zone1 = new WebPartZone();
zone1.ID = contr;
zone1.HeaderText = "myJone";
WebPartManager1.AddWebPart(myWebPart, zone1, 0);

}
But in this case design problem occurred, all zone added in same alingement
Plese help me so that I can make it like “igoogle” where user add control from other page and save it on main page

Unknown said...
This comment has been removed by a blog administrator.
Anonymous said...

hello i try to ope the webparts demo one and run it in vs2008 but got these error why plz???

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Anonymous said...

hello its really very nice demo but i try to open wepparts1 demo
but i got an error why ???

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

~SkyBlue~ said...

ASP.net futures link should be updated to this one: http://www.microsoft.com/downloads/thankyou.aspx?familyId=a5189bcb-ef81-4c12-9733-e294d13a58e6&displayLang=en

I was stuck finding the futures directory, turns out our link up there is out of date

Thx

Vipin Cherukara said...

Thanks , u helped me to solve the drag issue. I searched many wesites and blogs but none gave a solid solution. Your solution worked for me. thanks a lot

http://vipinc007.blogspot.com/

Mike, Zhang Mingquan said...

What a shame, M$ does not include support of non-IE browsers in .NET 4.0.

Steven HoO said...

I couldn't install Futures because I'm developing with .Net 4 Visual Studio 2010. Is there a workaround?

Thanks

Steven HoO said...

I couldn't install futures because i'm developing on .Net 4 Visual Studio 2010.

Is there a workaround?

thanks

Unknown said...

same here ,
i'm also developing on .Net 4 Visual Studio 2010.
Drag/Drop is not working for me too ... any news?

Priyanka said...

The link given in the blog is not working to download dll for drag and drop in FF. Just download above source code and get dll of microsoft.web.preview from that project

Venugopal said...

Just get the Microsoft.Web.Preview.dll file
1) Add the reference to .dll then you will get Microsoft.Web.Preview.dll in your Bin folder
===============
2) go to Web.config and write as
system.web>
pages ontrolRenderingCompatibilityVersion="4.0" clientIDMode="AutoID">
controls>
add namespace="Microsoft.Web.Preview.UI.Controls.WebParts" assembly="Microsoft.Web.Preview" tagPrefix="MSDLL"/>
/controls>
/pages>
/system.web>-->
========================

3) go to your souce code of your .aspx page and replace
=========
a) asp:WebPartManger> With MSDLL:WebpartManger>
/MSDLL:WebpartManger>

b)asp:WebpartZone> with MSDLL:WepPartZone>

And Run..
==================

4) if you get scripting Errors..
Add standard asp:ScriptManager>
in your page ...
Note: I removed Stating Tag "<" in my post Please Observe..
then RUN..
It will Works in all Browsers...

Krishna said...

Thanks for the posting this article,And Hoping can post related upgraded articles also.