'how to pass html table data to controller using jquery in asp.net mvc razor?
The Markup:
<div class="form-group">
<table class="table table-bordered" id="tblSavingColl" style="width: 97%; margin-left:1.5%;">
<thead>
<tr>
<th>Client Code</th>
<th>Name</th>
<th>Bal</th>
<th>Due</th>
<th>Received <br/>G S</th>
<th>Adj Y/N</th>
<th><input type="checkbox" id="selectall" /> All</th>
<th>GS Adj Amt</th>
<th>Bal</th>
<th>Due</th>
<th>Received SS</th>
<th>Adj Y/N</th>
<th><input type="checkbox" id="selectAll2" /> All</th>
<th>SS Adj Amt</th>
<th>Bal</th>
<th>Deposit</th>
<th>Withdraw</th>
<th>Rcvd</th>
<th>Prst</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="form-group">
<input type="button" class="button" id="btnSaveSaving" value="Save Saving Details" />
</div>
Javascript to load the table rows:
<script type="text/javascript">
$(document).ready(function(){
var savAcList = []; // to store ac infos
$.ajax({
type: 'GET',
url: '@Url.Action("GetSavingCollSheet", "CollectionSheetTranscation")',
dataType: 'json',
data: { adDate: $('#adDate').val(), centerCode: $('#centerCode').val(), collnSheetNo: $('#collnSheetNo').val() },
success: function (data) {
$.each(data, function (i, dets) {
var $row = $('<tr>' +
'<td>' + dets.clientNo + '</td>' +
'<td>' + dets.clientName + '</td>' +
'<td>' + dets.MSBal + '</td>' +
'<td>' + dets.MSDue + '</td>' +
'<td><input type="text" value = "' + dets.MSRec + '" class="chkBox" /></td>' +
'<td class="GSCol">' + msadjCheckBox + '</td>' +
'<td>' + msadjCode + '</td>' +
'<td>' + msadjAmount + '</td>' +
'<td>' + dets.PSBal + '</td>' +
'<td>' + dets.PSRec + '</td>' +
'<td><input type="text" value = "' + dets.PSRec + '" class="chkBox" /></td>' +
'<td class="SSCol">' + psadjCheckBox + '</td>' +
'<td>' + psadjCode + '</td>' +
'<td>' + psadjAmount + '</td>' +
'<td>' + dets.OSBal + '</td>' +
'<td>' + dets.OSDep + '</td>' +
'<td>' + dets.OSWithdraw + '</td>' +
'<td>' + recFlag + '</td>' +
'<td>' + prFlag + '</td>'
);
$('#tblSavingColl > tbody').append($row);
savAcList.push(dets.SavAcCode);
totMSDue += Number(dets.MSRec);
totPSDue += Number(dets.PSRec);
totOSDep += Number(dets.OSDep);
totOSWith += Number(dets.OSWithdraw);
totUFDue += Number(dets.UFRec);
psTransfer += Number(dets.PSAdjAmt);
msTransfer += Number(dets.MSAdjAmt);
if (dets.PresentFlag == "Y")
totPresent++;
});
var totalCollectionAmt = (totPSDue + totMSDue + totOSDep + totUFDue + 0 - (totOSWith + psTransfer + msTransfer));
$('#txttotalpensav').val(totPSDue);
$('#txttotaloptsav').val(totOSDep);
$('#txttotalwithdraw').val(totOSWith);
$('#txtpresent').val(totPresent);
$('#txttotalmonthsav').val(totMSDue);
$('#txttotunitfund').val(totUFDue);
$('#txttotalcolln').val(totalCollectionAmt);
$('#txtwelfarefundamt').val("0");
$('#txttotpentrans').val(psTransfer);
$('#txttotmontrans').val(msTransfer);
$('#txttotaltransfer').val(Number(psTransfer) + Number(msTransfer));
//alert(savAcList[0]);
},
error: function () {
alert("Error");
}
})
});
</script>
Question 1 Now after the table is loaded, we have checkbox in 6th column and 12th column. I needed to handle the checkbox event to
- When the checkbox in 6th column is checked, i must load a value in the dropdown in 7th column and the value of 5th column to 8th column.
- Similarly, when the checkbox in 12th column is checked, i must load a value in the dropdown in 13th column and the value of 11th column to 12th column.
For the value to load in dropdown i previously created an array called "savAcList" in jquery and fetched the value while loading table with data.
I am unable to find the checkbox column for doing the above. What I did is shown below, but the javascript below does a little bit of mis-steps like i need to check the first checkbox that is in 6th column then only the 12th column checkbox. And I when unchecking the checkbox, if the 12th column checkbox is unchecked it clears the value for 6th column and vice versa.
The javascript I did is :
var meroIndex = 0; var meroRow = 999;
$('#tblSavingColl').on('click', 'tr', function (e) {
//var myIndex = $('#tblSavingColl tr input[type="checkbox"]:checked').parent().index(); // get the index of the checkbox i.e. colIndex
var myIndex = $('#tblSavingColl tr input[type="checkbox"]').parent().index(); // get the index of the checkbox i.e. colIndex
var myRow = $(this).index(); // get the rowIndex
if (meroIndex == myIndex && myRow == meroRow)
myIndex = 12;
if (meroIndex == myIndex && myRow != meroRow)
myIndex = myIndex;
//alert("My Index " + myIndex + " MeroIndex = " + meroIndex);
meroIndex = myIndex;
meroRow = myRow;
var myTIndex = myIndex + 2;
var mySelIndex = myIndex + 1;
var ReceivedGS = $(this).find('td:nth-child(' + (Number(myIndex) - 1) + ') input').val();
var myAcCode = savAcList[Number(myRow)];
if ($(e.target).is('input[type=checkbox]')) {
var option = document.createElement("option"); // create a new element option [this here is created for a new option to be appended in the dropdownlist]
option.value = myAcCode; // associate the option element with value attribute
option.text = myAcCode; // associate the option element with text attribute
if ($(e.target).is(':checked')) // if the checkbox is checked
{
$(this).find('td:nth-child(' + myTIndex + ') input').val(ReceivedGS); // sets the textbox to the value in "ReceivedGS" variable
$(this).find('td:nth-child(' + mySelIndex + ') select').removeAttr("disabled"); // removes the disabled property of the dropdownlist
$(this).find('td:nth-child(' + mySelIndex + ') select').append(option); // append the option variable to the dropdownlist
$(this).find('td:nth-child(' + mySelIndex + ') select>option:eq(1)').attr('selected', true); // selects the newly created option of the dropdownlist
}
else // if the checkbox is not checked
{
$(this).find('td:nth-child(' + myTIndex + ') input').val("0"); // sets the textbox value to 0
$(this).find('td:nth-child(' + mySelIndex + ') select').find("option[value='" + myAcCode + "']").remove(); // removes the appended item from dropdownlist
$(this).find('td:nth-child(' + mySelIndex + ') select').prop("disabled", "disabled"); // applies the disabled property to the dropdownlist
}
}
});
I need the help for above.
And when I want to save the table data. I did stored all the rows and columns in an array and wanted to pass to the controller. This is all I did:
$('#btnSaveSaving').click(function () {
var myTableArray = [];
$('#tblSavingColl tbody tr').each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function () {
if ($(this).find("input[type=text]").length) {
var myText = $(this).find("input[type=text]").val();
arrayOfThisRow.push(myText);
}
else if ($(this).find("input[type=checkbox]").length) {
var myText = $(this).find("input[type=checkbox]");
if ((myText).prop('checked') == true)
arrayOfThisRow.push('Y');
else arrayOfThisRow.push('N');
}
else if ($(this).find("select").length) {
var myText = $(this).find("select :selected").text();
arrayOfThisRow.push(myText);
}
else arrayOfThisRow.push($(this).text());
});
myTableArray.push(arrayOfThisRow);
}
});
var params = [];
/*for (var i = 0; i < myTableArray.length; i++) {
var dataValue = myTableArray[i].split(',');
params = {
collSheetNo: $('#collnSheetNo').val(),
clientNo: dataValue[0],
clientCode: dataValue[0],
clientName: dataValue[1],
UFAcNo: dataValue[6],
UFBal: dataValue[2],
UFDue: dataValue[3],
UFRec: dataValue[4],
MSAcNo: dataValue[6],
MSBal: "a",
MSDue: "a",
MSRec: "a",
MSAdjFlag: "a",
MSAdjACNo: "a",
MSAdjCode: "a",
MSAdjAmt: "a",
PSAcNo: "a",
PSBal: "a",
PSDue: "a",
PSRec: "a",
PSAdjFlag: "a",
PSAdjAcNo: "a",
PSAdjCode: "a",
PSAdjAmt: "a",
OSAcNo: "a",
OSBal: "a",
OSDep: "a",
OSWithdraw: "a",
ReceivedFlag: "a",
PresentFlag: "a"
};
}*/
$.ajax({
type: 'POST',
url: '@Url.Action("SaveSavingColln", "CollectionSheetTranscation")',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ savingColln: params}),
success: function (result) {
alert(result);
},
error: function () {
alert("Error while saving Saving Collection Sheet");
}
});
});
The commented lines fills the params variable. But infact it does not execute after
var dataValue = myTableArray[i].split(',');
Question 2 So, i am having a problem while sending the data to controller as well. well i even tried the following way to pass the data to the controller.
data: JSON.stringify({ savingColln: myTableArray}),
I put a breakpoint on the controller to know whether or not the data is going to the controller or not. It actually reaches the controller and the length of the myTableArray but no value is fetch. My controller is as follows:
public JsonResult SaveSavingColln(List<SavingCollectionModel> savingColln)
{
string result = iCollService.SavingCollnSave(savingColln);
return Json(result, JsonRequestBehavior.AllowGet);
}
Solution 1:[1]
Please make sure that you have created proper json data to send server side.
Please try this
var str = JSON.stringify(myTableArray);
str = str.substring(0, str.length - 1).substring(1, str.length);
then pass this var str as data to server like below
data:'{"savingColln":'+str+'"}',
Hope this will solve the issue
Solution 2:[2]
I got the solution for passing the table data to the controller by doing the following:
$('#btnSaving').click(function(){
var myTableArray = [];
$('#tblSavingColl tr:not(:first)').each(function () {
var tds = $(this).find('td');
var myDets= { collSheetNo: $('#').val(), clientNo: $(tds[0]).html() }
myTableArray.push(myDets);
})
$.ajax({
type: 'POST',
url: '@Url.Action("SaveSavingColln", "CollectionSheetTranscation")',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(myTableArray),
success: function (result) {
alert(result);
},
error: function () {
alert("Error while saving Saving Collection Sheet");
}
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | halfer |

