Friday, July 3, 2009

Using JQuery UI Dialog with ASP.Net and AJAX Update Panel

One of the first things you will notice when you try and use JQuery UI Dialog in ASP.Net page is it does not perform post backs from within the dialog window. This is because in a ASP.Net page there is only one form element and Jquery appends the dialog "div" outside of the form element. There is a easy way to fix this. And once its done then its simple matter of combining some ASP.Net AJAX Update Panels and you are ready to go.

Lets look at a simple but non-trivial example of combining JQuery UI Dialog, Asp.Net and AJAX Update Panel. You can download the source of the sample here. Our sample application will display a list of names. To edit a name, you click on a name. 

This will pop up a JQuery UI Dialog with the current name. You can edit the name and click save. This will save and automatically close the dialog.   For adding a new Name, click on the "Add New Person" button. And this will bring up the new person dialog and allow you to save. Adding or Editing names will automatically update the list with the changes.









I am not going to go through explaining each line of the source. Its much easier to read the source code for yourself. I will just point out the main highlights. The first thing you will notices is when setting up the JQuery dialog, we are adding a open event to attach the dialog div to the form element. This will insure the post backs to happen.











Secondly, We set up update panels for each of the dialogues. It is important to note that the Update Panels are nested inside the dialog div. And also the GridView to display the list is also within an Update Panel. All of our update panels, UpdateMode is set as "Conditional" and ChildrenAsTriggers as "true". So they only update when some control within them posts back and we can also trigger the update by their Update method from the server side.

OK, now the code behind. To keep thing simple this example uses a Dictionary to store the names in the viewstate. Most of the code here is self explanatory. However I will point out the use of "ScriptManager.RegisterClientScriptBlock" to close the dialog. RegisterClientScriptBlock helps in adding javascript to be executed on asynchronous post back.

That's pretty much it. Give me a yell if you have any questions or some suggestions.

UPDATE: Also check out Using jQuery UI Tabs with ASP.Net MVC and Ajax Form Submit

Happy Coding

Ravi

Download Sample Code