Javascript – Totaling a GridView in ASP.NET

ajaxasp.netgridviewjavascript

In one of my ASP.NET Web Applications, I am using a BulkEditGridView (a GridView which allows all rows to be edited at the same time) to implement an order form. In my grid, I have a column which calculates the total for each item (cost x quantity) and a grand total field at the bottom of the page. Currently, however, these fields are only refreshed on every post-back. I need to have these fields updated dynamically so that as users change quantities, the totals and grand total update to reflect the new values. I have attempted to use AJAX solutions to accomplish this, but the asynchronous post-backs interfere with the focus on the page. I imagine that a purely client-side solution exists, and I'm hopeful that someone in the community can share.

Best Solution

If your calculations can be reproduced in JavaScript the easiest method would be using jQuery to get all the items like this:

$("#myGridView input[type='text']").each(function(){
  this.change(function(){
    updateTotal(this.value);
  });
});

Or if your calculations are way too complex to be done in JavaScript (or time restraints prevent it) then an AJAX call to a web service is the best way. Lets say we've got our webservice like this:

[WebMethod, ScriptMethod]
public int UpdateTotal(int currTotal, int changedValue){
  // do stuff, then return
}

You'll need some JavaScript to invoke the webservice, you can do it either with jQuery or MS AJAX. I'll show a combo of both, just for fun:

$("#myGridView input[type='text']").each(function(){
  this.change(function(){
    Sys.Net.WebServiceProxy.invoke(
      "/Helpers.asmx",
      "UpdateTotal",
      false,
      { currTotal: $get('totalField').innerHTML, changedValue: this.value },
      showNewTotal
    );
  });
});

function showNewTotal(res){
  $get('totalField').innerHTML = res;
}

Check out this link for full info on the Sys.Net.WebServiceProxy.invoke method: http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.Net/WebServiceProxyClass/WebServiceProxyInvokeMethod.aspx