Code snippet: Create JSON string from the web grid in MVC 4

The following JavaScript function returns the JSON string from the data of all displayed rows in the Web Grid control in the MVC framework.

You need to replace web grid id from the #employeeGrid in the third line of the function.

function gridTojson() {
        var json = '{';
        var otArr = [];
        var tbl2 = $('#employeeGrid tbody tr').each(function (i) {
 
            if ($(this)[0].rowIndex != 0) {
                x = $(this).children();
                var itArr = [];
                x.each(function () {
                    // Get the value from input control 
                    if ($(this).children('input').length > 0) {
                        itArr.push('"' + $(this).children('input').val() + '"');
                    }
                    else {
                        itArr.push('"' + $(this).text() + '"');
                    }
                });
                otArr.push('"' + i + '": [' + itArr.join(',') + ']');
            }
        })
        json += otArr.join(",") + '}'
 
        return json;
    }

You can modify the above function according to your need. From the above we assume that their is a editable column contains the input text control in the web grid control. If you have not any input control than you can modify .each() function as:

x.each(function () {
    itArr.push('"' + $(this).text() + '"');
    }
});

thanks