javascript - Tabular/nested(?) JSON collection and then accessing it on the server-side -
i have html table gets generated dynamically, looks this:
<table> <thead> <tr> <th>first name</th> <th>last name</th> <th>tel</th> </tr> </thead> <tbody> <tr id="11"> <td><input id="txt1" name="txt1" class="gridinput" type="text" field="firstname" value="a" /></td> <td><input id="txt2" name="txt2" class="gridinput" type="text" field="lastname" value="b" /></td> <td><input id="txt3" name="txt3" class="gridinput" type="text" field="tel" value="c" /></td> </tr> </tbody> </table>
i want iterate , store each table row item in json object, , pass server ajax. i've gotten far being able store , pass each individual input. (sorry, following concise can make it):
javascript function:
function savedata() { var gridinputs = { items: [ { field: "", val: "" } ] }; $('.gridinput').each(function () { gridinputs.items.push({ field: $(this).attr('field'), val: $(this).val() }); }); // send 'json.stringify(gridinputs)' server }
model:
public class gridinputroot { public list<gridinput> items { get; set; } } public class gridinput { public string field { get; set; } public string val { get; set; } }
web service method:
[webmethod(true)] public void savedata(string gridinputsjson) { gridinputroot gridinputs = jsonconvert.deserializeobject<gridinputroot>(gridinputsjson); foreach (var item in gridinputs.items) { string field = item.field; string val = item.val; // etc } }
how can change solution i'm looping through each row rather each cell on server side? key in whatever collection end unique - tr
's 'id' attribute
(i have thought of using linq group items etc there reasons why isn't ideal)
my approach work row-by-row:
/** * approach: resulting data structure. */ var example = [ { id: 11, // row id columns: [ {field: 'firstname', value: 'a'} // column in row. ] } ]; /** * approach: implementation. */ var rows = $('tr'); var table = []; rows.each(function () { var columns = this.children('td'); table.push({ id: this.id, columns: columns.map(function () { return {field: this.attr('field'), value: this.attr('value')}; }) }); });
now, in backend code:
[webmethod(true)] public void savedata(string gridinputsjson) { gridinputroot grid = jsonconvert.deserializeobject<gridinputroot>(gridinputsjson); foreach (var item in grid) { // row. foreach (var column in item.columns) { // column. string field = column.field; string val = column.val; } } }
my c# rusty, let's hope gets enough of way there.
Comments
Post a Comment