Home / AJAX

OData: HOW TO Update Data with an OData Service Using Ajax

RSS
Modified on 2010/03/10 01:38 by Shayne Burgess Categorized as Uncategorized
You can access an OData Service from an ASP.NET AJAX application by using the Sys.Data.OpenDataServiceProxy class. From client script, you can query and modify data that is exposed by a data service on the same Web site as the current page.

The example in this procedure shows an ASP.NET AJAX-enabled Web page that lets the user update a record in the Categories table of the Northwind database.

To run the example code in this topic, you will need the following:
  • The current release of ASP.NET AJAX, which you can download from the odata.org website.
  • The SQL Server Northwind sample database installed on your computer.
  • An OData feed that exposes the Northwind database. The easiest way to create this is to use WCF Data Services to create a service over the Northwind database. The service must be configured to allow reading from the Customers feed. For more information, see Data Service Quickstart.

Updating Data Through an OData Service

You can create a page that uses client script to update data through a data service.

To update data through the OData service

  1. Create a script element or JScript file that includes a client-script function that does the following:
    • Creates an instance of the OpenDataServiceProxy class.
    • Optionally, calls the query method to retrieve the data to be updated.
    • Creates the JavaScript object that contains the modified data.
      The following example shows a pageLoad function that creates an instance of the OpenDataServiceProxy class and calls the query method to retrieve all the records in the Categories table. The instance references a fictitious data service that has the relative URI /Northwind.svc. The call to query method references querySuccess as the succeeded callback function and cbFailure as the failed callback function. The succeeded callback function creates an array that contains the returned data records and builds the user interface to display the results.
      <script language="javascript" type="text/javascript">
      // The data service.
      var northwindService;
      // These variables hold references to the Categories
      // objects and their associated <li> elements.
      var categories;
      var categoryNodes;
      // On page load, populate the Categories list.
      function pageLoad() {
      northwindService =
      new Sys.Data.OpenDataServiceProxy("Northwind.svc");
      northwindService.query("Categories", querySuccess, cbFailure, userContext);
      }
      // Callback for a successful query; fill categories and
      // categoryNodes arrays.
      function querySuccess(result, context, operation, userContext) {
      var resultList = $get("resultList");
      resultList.innerHTML = "";
      categories = new Array();
      categoryNodes = new Array();
      for (var i in result) {
      var thisCategory = result[i];
      var li = document.createElement("li");
      categories[thisCategory.CategoryID] = thisCategory;
      categoryNodes[thisCategory.CategoryID] = li;
      li.appendChild(document.createTextNode(thisCategory.CategoryName + ": "
      + thisCategory.Description));
      li.innerHTML = li.innerHTML + ' <a href="javascript:doUpdate('
      + thisCategory.CategoryID + ')">[modify]</a>';
      resultList.appendChild(li);
      }
      }
      function cbFailure(result, context, operation) {
      alert(result);
      }
      </script>
  2. Add a function that calls the update method and passes the object with the data as a parameter.
    You can pass the relative URI of the resource that will receive the data. However, passing this value is not required if the object in the first parameter contains the identifier for the data record that you want to update. You can also pass references to callback functions for success and error conditions. In addition, you can pass an optional parameter with context or state, which is passed to the succeeded or failed callback function when the request returns.
    The following example shows a function named doUpdate that performs these tasks. The category variable includes a JavaScript object that contains category data from the data service and changes the Description property to the value from the user's input. The call to the update method references updateSuccess as the succeeded callback function to update the data on the Web page, and cbFailure as the failed callback function. The updateSuccess method adds the updated content to the Web page.
    function doUpdate(i) {
    var category = categories[i];
    var newDesc = prompt("Change description for category '"
    + category.CategoryName + "'.", category.Description);
    if (newDesc) {
    category.Description = newDesc;
    northwindService.update(category, updateSuccess,
    cbFailure, category /* pass category back as context */);
    }
    }
    // Callback for a successful update request.
    // Change categories and categoryNodes for this item.
    function updateSuccess(result, context, operation) {
    var oldChild = categoryNodes[context.CategoryID];
    var newChild = document.createElement("li");
    var resultList = $get("resultList");
    newChild.appendChild(
    document.createTextNode(context.CategoryName
    + ": " + context.Description));
    newChild.innerHTML = newChild.innerHTML +
    ' <a href="javascript:doUpdate(' + context.CategoryID
    + ')">[modify]</a>';
    resultList.replaceChild(newChild, oldChild);
    categoryNodes[context.CategoryID] = newChild;
    }
  3. On the Web page that you are using to invoke the OData service, add a script reference to the start.debug.js script that will automatically link the necessary references, as shown in the following example.
     <script type="text/javascript" src="scripts/start.debug.js"></script> 
    The following Sys.require statement referencing the required object must be also included:
    Sys.require([Sys.components.dataView,
    Sys.components.openDataContext, Sys.components.openDataServiceProxy]);
  4. If you created the JavaScript function in step 1 as a JScript file, add a reference to that file in the ScriptManager control. To register a static script file, set the Path property of the ScriptReference object to the relative location of the file, as shown in the following example:
     
    <asp:ScriptReference Path="scripts/UpdateExample.js" />
  5. Add any required user interface elements to the Web page.
    The following example shows the unordered list that is referenced by the JavaScript code that you created in step 1.
     
    <ul id="resultList">
    </ul>