.NET Performance Blog

February 2, 2010

ASP.NET GridView – edit records using JQuery Dialog

Filed under: .NET,ASP.NET,JQuery — Eric P @ 6:25 am

There are many ways in which you could modify modular data in Grid View:
1. Inline by making rows editable when u click on Edit
2. By using separate pages for Edit
3. By using popups/dialogs for adding/editing

In this post I will show how to implement the 3rd approach using JQuery UI Dialog for editing/adding data in ASP.NET GridView.

The following features have been implemented:
1. List customers
2. Add customer – Save/Cancel
3. Edit customer – Save/Cancel
4. Delete customer
5. Server side validation
6. Edit dialogs appear next to trigger links

You can check out the demo here:

The code is available here:


Data source

The grid lists customers which are stored in list which is initialized for each new session. This way each user trying out this sample will not affect other users.
CustomerService is a class wrapped around list of customers that allows to add/edit/list customers:

public class CustomerService
	private List<Customer> Customers
			List<Customer> customers;
			if (HttpContext.Current.Session["Customers"] != null)
				customers = (List<Customer>)HttpContext.Current.Session["Customers"];
				//Create customer data store and save in session
				customers = new List<Customer>();


				HttpContext.Current.Session["Customers"] = customers;

			return customers;

	public Customer GetByID(int customerID)
		return this.Customers.AsQueryable().First(customer => customer.ID == customerID);


Add/Edit dialog

There are two main operations that are handled using JQuery dialog
* Add Customer
* Edit Customer

In both cases the same dialog is used, as well as the same content div and Update Panel

	<div id="divEditCustomerDlgContainer">	
			<div id="divEditCustomer" style="display:none">
				<asp:UpdatePanel ID="upnlEditCustomer" runat="server">
						<asp:PlaceHolder ID="phrEditCustomer" runat="server">
							<table cellpadding="3" cellspacing="1">
									*First Name:
									<asp:TextBox ID="txtFirstName" Columns="40" MaxLength="50" runat="server" />
									*Last Name:
								<td colspan="2" align="right">
									<asp:Button ID="btnSave" onclick="btnSave_Click" Text="Save" runat="server" />
									<asp:Button ID="btnCancel" onclick="btnCancel_Click" onClientClick="closeDialog()" CausesValidation="false" Text="Cancel" runat="server" />
		</div>	<!-- divEditCustomerDlgContainer -->

You may notice that there are two divs around UpdatePanel – divEditCustomerDlgContainer and divEditCustomer. The reason for that is that when JQuery dialog opens – it is added after FORM tag in dom. That disables any ASP.NET submits and server side validation. The issue is described here:

To fix the issue I added a handler for JQuery Dialog open event that takes JQuery dialog DOM object and inserts it as a child of “divEditCustomerDlgContaine”. Note that JQuery dialog references divEditCustomer.

	<script type="text/javascript">
		$(document).ready(function() {
				autoOpen: false,
				modal: true,
				minHeight: 20,
				height: 'auto',
				width: 'auto',
				resizable: false,
				open: function(event, ui) {
					$(this).parent().appendTo("#divEditCustomerDlgContainer");    //This is where JQuery dialog is added to DlgContainer

When user clicks on Add/Edit customer links the following steps are followed:
1. JQuery dialog is opened
2. Content of dialog is overlayed with AJAX indicator and white background – BlockUI is used for that purpose
3. AJAX call is made that triggers refresh of upnlEditContent
4. On server side – dialog content is cleared for adding or loaded for editing.
5. Server side uses RegisterStartupScript to trigger a javascript call to UnlockDialog
6. Dialog is unlocked and available to user for editing

With this approach user sees the dialog right away and indicator tells him that data is being loaded. In most cases it should be pretty fast from click to being able to edit.

Positioning Dalog

You may notice that dialog appears to the right of the link that you click on. For that JQuery position() functionality is used:

	function openDialog(title, linkID) {
		var pos = $("#" + linkID).position();
		var top = pos.top;
		var left = pos.left + $("#" + linkID).width() + 10;
		$("#divEditCustomer").dialog("option", "title", title);
		$("#divEditCustomer").dialog("option", "position", [left, top]);

linkID is the ClientID of the link. Using the position() u can display dialog anywhere on the page or in relation to another control.

Running Client Side code using RegisterStartupScript in Async

To run some javascript script when response comes back from asynchronous request – function ScriptManager.RegisterStartupScript can be used.

The issue is that the first parameter in:
RegisterStartupScript Method (Control, Type, String, String, Boolean)

must be a control in update panel that will be rendered on the current request. In the “List Customers” page there are two update panels -“upnlEditCustomers” and “upnlCustomers” (for grid view).
The first panel is always updated on any async request (UpdateMode=”Always” by default). Originally I though to make it conditional which would be more efficient, but there were some issues to resolve and I decided it wasn’t worth the trouble in this case. As for “upnlCustomers” – we definitely don’t want that re-rendered on every async request – like opening/canceling the dialog, so this one is set to update conditionally.

To get RegisterStartupScript to work without worrying that triggering conrol is rendered in current request, I added another UpdatePanel whose sole purpose is to facilitate JavaScript calls from Async requests. This panel has an empty placeholder that’s used as a control in RegisterStartupScript:

	<asp:UpdatePanel ID="upnlJsRunner" UpdateMode="Always" runat="server">
			<asp:PlaceHolder ID="phrJsRunner" runat="server"></asp:PlaceHolder>

On server side there is a function RegisterStartupScript(key, script) that uses update panel above:

	private void RegisterStartupScript(string key, string script)
		ScriptManager.RegisterStartupScript(phrJsRunner, phrJsRunner.GetType(), key, script, true);

        private void TriggerClientGridRefresh()
		string script = "__doPostBack(\"" + btnRefreshGrid.ClientID + "\", \"\");";
		RegisterStartupScript("jsGridRefresh", script);   //Trigger async grid refresh on Save

	private void HideEditCustomer()
		RegisterStartupScript("jsCloseDialg", "closeDialog();");    //Close dialog on client side

Clear data in dialog

When user clicks on “Add Customer” – data in dialog is cleared and all validators are reset to Valid. For this I wrote a function that loops through all the controls in dialog and then performs a certain action on the controls of certain type:

	private void ClearEditCustomerForm()
		//Empty out text boxes
		var textBoxes=new List<Control>();
		FindControlsOfType(this.phrEditCustomer, typeof(TextBox), textBoxes);
		foreach (TextBox textBox in textBoxes)
			textBox.Text = "";

		//Clear validators
		var validators=new List<Control>();
		FindControlsOfType(this.phrEditCustomer, typeof(BaseValidator), validators);
		foreach (BaseValidator validator in validators)
			validator.IsValid = true;

	static public void FindControlsOfType(Control root, Type controlType, List<Control> list)
		if (root.GetType() == controlType || root.GetType().IsSubclassOf(controlType))

		//Skip input controls
		if (!root.HasControls())

		foreach (Control control in root.Controls)
			FindControlsOfType(control, controlType, list);

Right now it only handles TextBoxes and Validators, but it can be easily expanded to support Text Areas, Drop Downs, etc…

JQuery Includes

This sample doesn’t include the files for JQuery UI and JQuery base library. Instead those are referenced at the google AJAX CDN.
The approach for including JQuery UI from Google AJAX CDN is covered here: http://encosia.com/2009/10/11/do-you-know-about-this-undocumented-google-cdn-feature/

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/start/jquery-ui.css" type="text/css" rel="Stylesheet" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>

This makes the application and code download a lot smaller (a lot less files), so it is great for sample projects.


Create a free website or blog at WordPress.com.