Hello everyone, I have a sample table that I want to share:
<table class="table table-bordered" width="100%" cellspacing="0" id="tableID">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center">val1</td>
<td align="center">val2</td>
<td align="center">val3</td>
<td align="center">1500</td>
<td align="center" class="myID"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" value="" min="0" max="1000"></td>
</tr>
<tr>
<td align="center">val1</td>
<td align="center">val2</td>
<td align="center">val3</td>
<td align="center">1500</td>
<td align="center" class="myID"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" value="" min="0" max="1000"></td>
</tr>
<tr>
<td align="center">val1</td>
<td align="center">val2</td>
<td align="center">val3</td>
<td align="center">1500</td>
<td align="center" class="myID"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" value="" min="0" max="1000" ></td>
</tr>
</tbody>
</table>
<form>
<button type="button" onclick="aplicar()">Apply</button>
</form>
<script>
function setValueAttr(el){
el.setAttribute('value', el.value)
}
function aplicar(){
var myTab = document.querySelectorAll('#tableID tbody tr .txtID:not([value=""])');
var tableData = [];
Array.from(myTab).forEach(input => {
var tds = input.closest('tr').children;
var obj = {};
obj.A = tds[0].textContent;
obj.B = tds[1].textContent;
obj.C = tds[2].textContent;
obj.D = tds[3].textContent;
obj.E = input.value;
tableData.push(obj);
});
tableData = JSON.stringify({ 'tableData': tableData });
$.ajax({
url: '@comercial.Models.Base.DirectorioRaiz()Controller/View',
type: 'post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: tableData,
success: function (response) {
$('#divPagosAplicados').html(response);
},
error: function (error) {
console.log(error);
}
});
}
</script>
I found a way to receive this JSON in my controller:
public class tableData
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
public string D { get; set; }
public string E { get; set; }
}
public void View(List<tableData> tableDatas)
{
var t = tableDatas;
}
However, I need to perform an operation similar to the JavaScript function in my controller:
var total = [];
for (i = 0; i < tableData.length; i++) {
total[i] = "&num_operacion" + (i + 1) + "=" + tableData[i].A +
"&monto" + (i + 1) + "=" + tableData[i].E +
"&num_documento" + (i + 1) + "=" + tableData[i].B +
"&tipo_documento" + (i + 1) + "=" + tableData[i].C
}
I achieved this using JavaScript and sending the string with POST, but if the string is large, AJAX will crash.