如何在mvc razor中使用jquery将html表格数据传递给控制器asp.net?

d8tt03nd  于 2023-01-08  发布在  jQuery
关注(0)|答案(2)|浏览(131)

标记:

<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:

<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>

问题1现在,加载表后,我们在第6列和第12列中有复选框。我需要处理复选框事件以

1.当第6列的复选框被选中时,我必须在第7列的下拉列表中加载一个值,并从第5列加载到第8列。
1.同样,当第12列的复选框被选中时,我必须在第13列的下拉列表中加载一个值,并将第11列的值加载到第12列。
对于要加载到下拉列表中的值,我之前在jquery中创建了一个名为“savAcList”的数组,并在加载包含数据的表时获取了该值。
我无法找到复选框列做以上。我所做的是如下所示,但下面的javascript做了一点错误的步骤,如我需要选中第一个复选框,这是在第6列,然后只有第12列复选框。当我取消选中复选框,如果第12列复选框是未选中它清除值为第6列,反之亦然。
我写的javascript是:

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
        }
    }
});

我需要上面的帮助。
当我想保存表数据时,我确实把所有的行和列都存储在一个数组中,并想传递给控制器,这就是我所做的一切:

$('#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");
        }
    });
});

注解行填充了params变量,但实际上它并没有在

var dataValue = myTableArray[i].split(',');

问题2所以,我有一个问题,而发送数据到控制器以及。嗯,我甚至尝试了以下方式将数据传递到控制器。

data: JSON.stringify({ savingColln: myTableArray}),

我在控制器上放置了一个断点,以了解数据是否会进入控制器。它实际上到达了控制器和myTableArray的长度,但没有获取任何值。我的控制器如下所示:

public JsonResult SaveSavingColln(List<SavingCollectionModel> savingColln)
    {
        string result = iCollService.SavingCollnSave(savingColln);
        return Json(result, JsonRequestBehavior.AllowGet);
    }

6l7fqoea

6l7fqoea1#

请确保您已经创建了正确的json数据以发送到服务器端。
请试试这个

var str = JSON.stringify(myTableArray);
str = str.substring(0, str.length - 1).substring(1, str.length);

然后将此var str作为数据传递到服务器,如下所示

data:'{"savingColln":'+str+'"}',

希望这能解决问题

vyu0f0g1

vyu0f0g12#

我通过执行以下操作得到了将表数据传递给控制器的解决方案:

$('#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");
        }
    });
});

相关问题