Click here to Skip to main content
14,875,773 members
Articles / Web Development / HTML
Posted 19 Oct 2007


95 bookmarked

Light Speed Inline Editing Using ASP.NET AJAX and Web Services: Part I

Rate me:
Please Sign up or sign in to vote.
4.81/5 (21 votes)
6 Apr 2008CPOL6 min read
JavaScript + AJAX solution for inline editing in a grid.

Screenshot - grid.gif


If you ask people what the most important thing that they want for web based application UIs, most of them will answer "I want to edit data really fast, like in Excel!" That is a tough request. It means that the person wants to click on a row, edit some data, then click on another row, and have all the data saved into a database. We've found a solution for this during TargetProcess v.2.6 development. TargetProcess is a great agile project management software (if you are not aware ;)


The ASP.NET framework provides inline editing functionality in GridView. But sometimes, you get into situations when you cannot use this functionality:

  • You cannot use it with a disabled View State.
  • Performance is really bad. When you click a button to switch the row into edit state, a post back to the server will be initiated. The post back will happen when you save or cancel the edit mode as well. Even if you put your grid into an UpdatePanel, AJAX.NET still will update the whole grid instead of just one row, and the size of the date in the post back remains almost the same (and large).

With bad performance, it will not be like Excel, right? So, we have to look for a solution that:

  • Will not initiate post back to the server
  • Will work with a disabled view state
  • Will be as fast as Excel (at least, less than a second to do an action)


The Inline Edit Controller (IEC) is JavaScript solution that resolves all our problems (you will see it really soon). It has the following advantages:

  • It's a cross-platform solution, you can use it in any environment: ASP, ASP.NET, PHP, JSP etc.
  • It's a cross-browser solution.
  • It's a very extensible solution; it's pretty simple to extend the basic behavior by adding your custom handlers.
  • It can be easily integrated into existing applications without almost any rework. You can define custom saving methods to put edited values into a database.

Basic principles

IEC is a plain JavaScript solution that allows editing rows in a grid. In order to have an editable row, you should mark the row in some specific manner. Let's call this stuff "Inline Edit Panel". It contains a button that enables inline editing as well as buttons that save changes and cancels editing. In fact, the better way to go is to enable editing on double click, and cancel it on Escape key. That will be shown in more advanced examples. So far, we have simple buttons:

<asp:GridView CellPadding="0" CellSpacing="0" Width="1px" 
       GridLines="none" runat="server" AllowSorting="false" 
       AutoGenerateColumns="false" ID="uxOrders">
            <span runat="server" style="white-space: nowrap" 
                  class="inlineEditIcon" inlineeditattribute="true" 
                  rowid='<%# Eval("OrderID")%>'>
              <img runat="server" action="edit" 
                   title="Inline Edit" src="~/img/edit.gif" />
              <img runat="server" style="display: none" 
                   action="save" title="Save" src="~/img/save.gif" /> 
              <img runat="server" style="display: none" 
                   action="cancel" title="Cancel" src="~/img/cancel.gif" />

Cells that are going to be editable must be located in a specific place holder as well. Let's call this stuff "Edit Area".

<asp:TemplateField HeaderText="Freight">
          <span id="FreightIdPrefix<%# Eval("OrderID")%>">
        <asp:Label ID="Label1" runat="server" 

As you can see, the "Inline Edit Panel" has three buttons, with an extra "action" attribute. Each action attribute fires the corresponding event. The IEC handles all these events and makes the corresponding changes in the DOM. Let's review the editing process now.

1. User clicks the Edit button

  • At this stage, the row switches to an editable state, and input and select boxes are appended to "Edit Areas".
  • The usual text labels become invisible. It means that the Freight label in the code above becomes invisible, and the input text field is added to the span with id="FreightIdPrefix777".

2. User changes some values and clicks the Save button

  • At this stage, IEC extracts all the values from editable fields (input, select, other if any).
  • Replace the label texts with new values from the editable fields.
  • Create a JavaScript object that holds the edited (new) values.
  • It's time to save changes into the database. IEC has no idea how to save new data, so it just passes the JavaScript object that holds the new values into the saving method.

3. User pushes the Cancel button

  • At this stage, IEC removes editable fields ("input", "select").
  • Labels become visible again.

Usage example

The idea looks really simple. But maybe, the solution is hard to use, who knows… Only a real example can help us judge the solution.

Let's take an ASP.NET example with:

  • A GridView control to present the data.
  • A Web Service to retrieve the data and save the modified data.
  • AJAX.NET to generate web methods that can be used from JavaScript.
  1. For example, we have a pretty simple Order class. We want to show all the orders in a grid.

    Screenshot - orderCRC.jpg

  2. The GridView initialization is a no-brainer as well. OrderService is a class that can retrieve orders from the database (we don't care how; maybe the GetAllOrders method uses NHibernate, or maybe plain old SQL).
    protected override void OnLoad(EventArgs e)
      if (!IsPostBack)
         OrderService orderService = new OrderService();
         Order[] orders = orderService.GetAllOrders();
         uxOrders.DataSource = orders;
  3. IEC mapping. As mentioned above, we should add columns with inline editing controls (Inline Edit Panel).
           <span id="Span1" runat="server" style="white-space: 
                 nowrap" class="inlineEditIcon" inlineeditattribute="true"  
              rowid='<%# Eval("OrderID")%>'> 
              <img id="Img1" runat="server" action="edit" 
                   title="Inline Edit" src="~/img/edit.gif" /> 
              <img id="Img2" runat="server" style="display: none" 
                   action="save" title="Save" src="~/img/save.gif" />
              <img id="Img3" runat="server" style="display: none" 
                   action="cancel" title="Cancel"    
              src="~/img/cancel.gif" />                       

    And insert all the required "Edit Areas".

    <asp:GridView CellPadding="0" CellSpacing="0" Width="1px" 
                  GridLines="none" runat="server" AllowSorting="false" 
                  AutoGenerateColumns="false" ID="uxOrders">
                       <span priorityname='<%#Eval("Priority")%>' 
                             id="PriorityIdPrefix<%# Eval("OrderID")%>">
             <asp:TemplateField HeaderText="Freight">
                       <span id="FreightIdPrefix<%# Eval("OrderID")%>">
                       <asp:Label ID="Label1" runat="server" 
              <asp:TemplateField HeaderText="Ship Name">
                           <span id="ShipNameIdPrefix<%# Eval("OrderID")%>">
                            <asp:Label ID="Label1" runat="server" 

    As you can see, the "Edit Areas" have a composite ID that consists of two parts: "Edit Area prefix + itemID". Such an ID is required to make each row unique.

  4. Now, we should create an IEC instance, and the EditAreaSettings instances (see below) for each "Edit Area".
    var editAreasSettings = new Array();
    //ShipName is a property of Order class
    //ShipNameIdPrefix is an id of span element
    //(EditArea of ShipName property)   
    var shipNameEditAreaSettings = new EditAreaSettings("ShipName", 
                                   "ShipNameIdPrefix",null, true);
    var freightSettings = new EditAreaSettings("Freight","FreightIdPrefix");
    freightSettings.onSelectValue = onSelectFreightValueHandler;
    var prioritySettings = new EditAreaSettings("Priority",
    prioritySettings.onRenderEditedValue = onRenderPriorityValue; 
    prioritySettings.onSelectValue = onSelectPriorityValue;
    var inlineEditController = new InlineEditController('<%=uxOrders.ClientID%>', 
                               editAreasSettings, onSaveEventHandler, true);

    EditAreaSettings( areaName, areaPrefix , dataSourceControlID, isFocused)


    • areaName – used by IEC to map the edited values to the retObj that is passed into onSaveEventHandler.
    • areaPrefix – used by IEC to find the edit area.
    • dataSourceControlID – data source control ID that has a collection of predefined values.
    • isFocused - boolean value that specifies whether the edit area will have a focus.

    onRenderPriorityValue and onSelectPriorityValue are custom handlers that are implemented outside of IEC. It is impossible to implement all the cases of editing, and for specific situations, you have to create custom handlers. For example, the Priority column is an image. When the row is in the usual state, it shows the priority icon, but when the row is in an editable state, it should show the select box.

    Screenshot - priority.jpg

    The code of onRenderPriorityValue and onSelectPriorityValue are out of the scope for this article; it will be described in Part II (architecture, extensibility, and stuff like that).

  5. We are getting closer to the final. Let's add the saving handler. IEC is quite agnostic to data saving, and does not care how you will implement that. All it needs is a method call that does all the job.
    function onSaveEventHandler(retOb)
        retObj.OrderID  = retObj.itemID;

    The UpdateOrder method will be fired on the save event. It has only one input parameter, retObj, which holds all the edited values. IEC maps the edited values into retObj using the keys from EditAreaSettings (for example, shipName, Freight). Fortunately, I mapped the "Edit Areas" for IEC to be consistent with the Order class, except retObj.itemID that is created by IEC. As a result, retObj can be casted to the Order class. I had to do one extra assignment to make retObj completely consistent with Order.

    retObj.OrderID = retObj.ItemID

    The onSaveEventHandler handler is completely consistent with the web method.

    public class OrderService : WebService
        public string UpdateOrder(Order order)
            OrderDao OrderDao = DaoFactory.GetDaoFactory().GetOrderDao();
            bool isUpdated = OrderDao.UpdateOrder(order);
            if (isUpdated)
                return "The order '" + order.OrderID + "' is successfully updated.";
                return "Unable to find order '" + order.OrderID + "'.";

I'm using the web service to save the order, but it's not necessary. It's a pretty flexible approach that allows other mechanisms to save the data.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Andrew Golik
Web Developer
Belarus Belarus
Andrew Golik is a software professional working in Minsk, Belarus.
He enjoys design infrastructures based on object oriented paradigm. His programming experience includes ASP, ASP.NET, .NET, COM, JAVA, PHP, DHTML, AJAX, blah blah blah....

Andrew Golik's Blog

Comments and Discussions

QuestionWrite back to SQL Database? Pin
Member 959977714-Nov-12 10:43
MemberMember 959977714-Nov-12 10:43 
QuestionHow to pre populate a column using javascript Pin
NithinShetty7419-Apr-12 7:30
MemberNithinShetty7419-Apr-12 7:30 
Questiongetting error in this.... Pin
Anupam Singh22-Nov-11 18:46
MemberAnupam Singh22-Nov-11 18:46 
GeneralWhere is the Ajax? Also no web config setting. Pin
msdevtech10-Sep-10 2:26
Membermsdevtech10-Sep-10 2:26 
Maybe I am missing something here but I don't see where this is Ajax. Also there is no web config setting for your web service for data access. I had to figure out and add the following to my web service, web config.

<add key="DaoFactory" value="TargetProcess.DaoTraining.DataAccessLayer.XmlRepository.XmlDaoFactory">

GeneralWow very impressive! Pin
Kyryll99930-Aug-10 13:39
MemberKyryll99930-Aug-10 13:39 
GeneralMy vote of 2 Pin
JimShermerhorn19-Jan-10 17:20
MemberJimShermerhorn19-Jan-10 17:20 
Questionmore info Pin
vmarko2-Dec-08 20:54
Membervmarko2-Dec-08 20:54 
QuestionSave Method [modified] Pin
Khunah1-Aug-08 3:10
MemberKhunah1-Aug-08 3:10 
GeneralKlevo Pin
Kasim P23-Oct-07 3:56
MemberKasim P23-Oct-07 3:56 
GeneralRe: Klevo Pin
Andrew Golik25-Oct-07 4:01
MemberAndrew Golik25-Oct-07 4:01 
GeneralRe: Klevo Pin
Kasim P6-Nov-07 3:22
MemberKasim P6-Nov-07 3:22 
GeneralGood approach Pin
MR_SAM_PIPER22-Oct-07 14:23
MemberMR_SAM_PIPER22-Oct-07 14:23 
GeneralRe: Good approach Pin
firefalcon22-Oct-07 22:06
Memberfirefalcon22-Oct-07 22:06 
GeneralRe: Good approach Pin
Andrew Golik25-Oct-07 4:19
MemberAndrew Golik25-Oct-07 4:19 
GeneralRe: Good approach [modified] Pin
Andrew Golik25-Oct-07 4:40
MemberAndrew Golik25-Oct-07 4:40 
GeneralReally Cool Stuff! Pin
firefalcon19-Oct-07 0:24
Memberfirefalcon19-Oct-07 0:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.