Javascript – Gridview manipulation using JQuery and JavaScript

asp.netgridviewjavascriptjquery

I have an ASP.NET gridview I want to manipulate using JavaScript/JQuery. The problem I THINK I'm going to have with my approach is that the server won't have any knowledge of the rows that I am appending via gridview since the html representation of the gridview control is coupled with the object model that lives on the server. So here is what I need to do:

I need to append to the gridview when a user submits data, and submit each row in the batch of entered data to the server to be processed. Because I have other ASP.NET controls that will contain data that I want to submit, I'd like to submit all that data via a traditional postback to the server.

  1. How do I implement this approach if possible?
  2. If not possible, could you please explain?

Thank you very much for your help.

Best Answer

var queryString = "";

// This could be based on a number of different events
$('#finishButton').click(function(){

    // Iterate through each input (you could add other form elements)
    $('#myForm input').each(function(){

        // Build your query string to post to your aspx page
        queryString += $(this).attr("name") + "&" + $(this).val() + ",";

    });
});

// Make sure special chars are escaped
queryString = escape(queryString);

// POST the form to your aspx page
$.ajax({ 
    type: 'POST', 
    url: 'myFormProcessor.aspx', 
    data: queryString,
    // Upon a successful POST, successHandler will be called 
    success: successHandler 
});

// Add the new data to the grid
function successHandler(){

    // Clone the last row
    $('#myTable tr:last').clone(true).insertAfter('#myTable tr:last');

    // Here you could just break apart the query 
    // string you build in the above code
    // and use those values to change the values 
    // in the row you added to the grid

}

Make sure to unescape the query string in your aspx page, and then break it up by the delimiters you're using. I used '&' to separate key/value and commas between variables (inputs).