【问题标题】:How to create cascading dropdown list inside dynamically added table row and save in the database如何在动态添加的表行中创建级联下拉列表并保存在数据库中
【发布时间】:2019-05-24 08:29:26
【问题描述】:

我在表格中添加了动态行,其中包含相互依赖的下拉列表(级联)。我可以使用这些下拉列表成功添加动态行,但问题是如何根据第一个下拉列表(类别)中的选定值填充第二个下拉列表(子类别)的值? [请看这张图]:https://imgur.com/sKQ304k

我已经可以在第一个下拉列表中填充值,该下拉列表中的值来自数据库,但我仍在寻找一种方法来填充第二个下拉列表中的值。我尝试使用硬编码值填充数据(请参见下面的代码)并且它运行正常。但是当我在数据库中获取值时,这就是我苦苦挣扎的地方。

控制器

 //To populate data in second dropdown list
 public ActionResult GetPSESubcategories(Guid pse_category_id)
    {
        List<SelectListItem> subCategories = new List<SelectListItem>();
        var subCategoryList = PopulateDropdown.GetPSESubcategory(pse_category_id);
        return Json(subCategoryList, JsonRequestBehavior.AllowGet);
    }

查看

<div class="row" style="display:none;" id="patientExperienceDiv">
    <div class="table-responsive" style="padding-left:8px !important;">
        <table class="table">
            <thead>
               <tr>
                 <th style="border-bottom:none !important;border-top:none !important;">
                    <text style="font-weight:500 !important;"><strong>II.</strong>&nbsp;Categories</text><br />
                    <text style="font-size:12px;color:#a5a5a5;font-weight:400 !important;">Please select.</text>
                 </th>
                 <th style="border-bottom:none !important;border-top:none !important;">
                    <text style="font-weight:500 !important">Subcategories</text><br />
                    <text style="font-size:12px;color:#a5a5a5;font-weight:400 !important;">Please select.</text>
                 </th>
                 <th style="border-bottom:none !important;border-top:none !important;"></th>
                 <th style="border-bottom:none !important;border-top:none !important;"></th>
                 <th style="border-bottom:none !important;border-top:none !important;"></th>
               </tr>
             </thead>
             <tbody id="multipleCategoryTbl">
               <tr>
                 <td style="border-bottom:none !important;border-top:none !important;">
                     <div style="padding-top:2px">                                                            
                        @Html.DropDownListFor(a => a.addedCategory, new SelectList(ViewBag.PSECategories, "Value", "Text"), "Select Category", new { @class = "form-control", @id ="cat" })
                      </div>
                  </td>
                  <td style="border-bottom:none !important;border-top:none !important;">
                     <div style="padding-top:2px;">
                        @Html.DropDownListFor(a => a.addedSubcategory, new SelectList(ViewBag.PSESubcategories, "Value", "Text"), "Select Subcategory", new { @class = "form-control field", @disabled = "disabled", @id = "sub" })
                        @Html.EditorFor(a => a.addedSubcategory, new { htmlAttributes = new { @class = "form-control field", @readonly = "readonly", @id = "nature", @style = "display:none;" } })
                      </div>
                   </td>
                   <td style="border-bottom:none !important;border-top:none !important;">
                       <button type="button" class="form-control btn btn-default btn-sm" id="addNewCategoryBtn" style="text-align:center !important;">
                       <i class="fa fa-plus"></i>
                       </button>
                   </td>
                   <td style="border-bottom:none !important;border-top:none !important;">
                       <button type="button" class="form-control btn btn-default btn-sm" id="removeNewCategoryBtn" onclick="remove_row('multipleCategoryTbl')" style="text-align:center !important;">
                       <i class="fa fa-remove"></i>
                       </button>
                    </td>
                    <td style="border-bottom:none !important;border-top:none !important;"><input type="text" class="form-control" id="textId" name="ids" value="0" /></td>
                </tr>
             </tbody>
          </table>
</div>

JAVASCRIPT

<script>
   $(function () {
       $('#cat').change(function () {
           getSelectedItem(this, null);
       });

       $('#addNewCategoryBtn').click(function () {
           addRow('multipleCategoryTbl');
       });

       //sample hard-coded values that must be replaced by javascript on cascading dropdown list values from database
       var jsonObj = { "category1": ["subcat 1"], "category2": ["subcat 2.1", "subcat 2.2"], "category3": ["subcat 3.1", "subcat 3.2", "subcat 3.3"] };
       var keys = Object.keys(jsonObj);

       var category_dropdown = document.getElementById("cat");

       var getSelectedItem = function (element, row) {
           $("#sub").prop("disabled", false);

           var e = element;
           var selectedCategory = e.options[e.selectedIndex].value;
           alert(selectedCategory);    //selected value in the first dropdown list

           var sub_category_dropdown = (row != null ? row.getElementsByTagName("select")[1] : document.getElementById("sub"));

          alert(sub_category_dropdown.nodeValue); //check the values of second dropdown list

          sub_category_dropdown.options.length = 0;

          for (var i = 0; i < jsonObj[selectedCategory].length; i++) {                                                
             sub_category_dropdown[sub_category_dropdown.length] = new Option(jsonObj[selectedCategory][i], jsonObj[selectedCategory][i]);
          }
        };

        //to dynamically add table rows
        var addRow = function (tableID) {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var colCount = table.rows[0].cells.length;

        for (var i = 0; i < colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[0].cells[i].innerHTML;

            newcell.childNodes[0].selectedIndex = 0;
        }
        var selects = row.getElementsByTagName("select");
        selects[0].addEventListener('change', function () { getSelectedItem(this, row) }, false);
        };

        //this must be the place where the values of second dropdown is populated
        for (var keys in jsonObj) {                                     
        category_dropdown[category_dropdown.length] = new Option(keys, keys);
        }
   });

这是我为级联下拉列表制作的单独 javascript,但我不知道在 getSelectedItem 函数中插入的位置

$("#cat").on('change', function () {
        alert($(this).val());

        $("#sub").prop("disabled", false);
        $("#sub").empty();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetPSESubcategories", "PSERegistry")',
            dataType: 'json',
            data: { pse_category_id: $(this).val() },
            success: function (subCategories) {
                $("#sub").append($('<option></option>').val('').text('Select Subcategory'));
                $.each(subCategories, function (i, sub) {
                    $("#sub").append('<option value ="' + sub.Value + '">' + sub.Text + '</option>');
                });

                //Update the data in subcategory dropdown upon selection of category
                $("#sub").trigger("chosen:updated");
                $("#sub").trigger("liszt:updated");
            },
            error: function () {
                alert('Please select Category.');
            }
        });
        return false;
    });

更新:

我修改了用于级联下拉列表的 javascript,这就是我所拥有的,

<script>

    $('#cat').change(function () {
        alert('test');
        getSelectedItem(this, null);
    });

    var category_dropdown = document.getElementById("cat");

    function getSelectedItem(element, row) {
        $("#sub").prop('disabled', false);
        $("#sub").empty();                                   

        var e = element;
        var selectedCategory = e.options[e.selectedIndex].value;
        alert(selectedCategory);

        $.ajax({
             type: 'POST',
             url: '@Url.Action("GetPSESubcategories", "PSERegistry")',
             dataType: 'json',
             data: { pse_category_id: selectedCategory },
             success: function (subCategories) {

                 var sub_category_dropdown = (row != null ? row.getElementsByTagName("select")[1] : document.getElementById("sub"));
                 sub_category_dropdown.options.length = 0;

                 $("#sub").append($('<option></option>').val('').text('Select Subcategory'));
                 $.each(subCategories, function (i, sub) {

                 sub_category_dropdown[sub_category_dropdown.length] = new Option(sub.Text, sub.Value);
                                                //alert(sub.Value);
                 });
              },
              error: function () {
                 alert('Please select Category.');
              }
           });
         };

         function addRow(table_id) {
            alert('new row added');

            var table = document.getElementById(table_id);

            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);

            var colCount = table.rows[0].cells.length;
            alert(rowCount);

            for (var i = 0; i < colCount; i++) {

                var newcell = row.insertCell(i);

                newcell.innerHTML = table.rows[0].cells[i].innerHTML;
                //alert(newcell.innerHTML);
                //alert(newcell.childNodes[0].type);

                switch (newcell.childNodes[0].type) {
                    case "text":
                        newcell.childNodes[0].value = rowCount;
                    case "checkbox":
                        newcell.childNodes[0].checked = false;
                        break;
                    case "select":
                        newcell.childNodes[0].selectedIndex = 0;
                        break;
                }
             }

             var selects = row.getElementsByTagName("select");
             selects[0].addEventListener('change', function () {
                 alert('clicked');
                 getSelectedItem(this, row)
             }, false);
          }

动态添加行内的级联下拉菜单已经在运行,但每当我在其他行的其他下拉列表中选择时,第一行(动态添加期间要复制的原始行)都会受到影响。

有人可以帮我解决这个问题吗? 提前谢谢你。

【问题讨论】:

    标签: javascript c# asp.net-mvc


    【解决方案1】:

    已经找到了我的问题的解决方案。这就是我所做的,

    查看

    <div class="row" style="display:none;" id="patientExperienceDiv">
        <div class="table-responsive" style="padding-left:8px !important;">
            <table class="table" id="pxeTable">
               <thead>
                  <tr>
                    <th style="border-bottom:none !important;border-top:none !important;">
                       <text style="font-weight:500 !important;"><strong>II.</strong>&nbsp;Categories</text><br />
                       <text style="font-size:12px;color:#a5a5a5;font-weight:400 !important;">Please select.</text>
                    </th>
                    <th style="border-bottom:none !important;border-top:none !important;">
                        <text style="font-weight:500 !important">Subcategories</text><br />
                        <text style="font-size:12px;color:#a5a5a5;font-weight:400 !important;">Please select.</text>
                     </th>
                     <th style="border-bottom:none !important;border-top:none !important;"></th>
                     <th style="border-bottom:none !important;border-top:none !important;"></th>
                     <th style="border-bottom:none !important;border-top:none !important;"></th>
                     <th style="border-bottom:none !important;border-top:none !important;"></th>
                     </tr>
                </thead>
                <tbody id="pxeTbody">
                     <tr>
                        <td style="border-bottom:none !important;border-top:none !important;">
                           @Html.DropDownListFor(a => a.pxeAddedCategory, new SelectList(ViewBag.PSECategories, "Value", "Text"), "Select Category", new { @class = "form-control pxeCategoryDDL", @id = "pxeCategoryList" })
                        </td>
                        <td style="border-bottom:none !important;border-top:none !important;">
                            @Html.DropDownListFor(a => a.pxeAddedSubcategory, new SelectList(ViewBag.PSESubcategories, "Value", "Text"), "Select Subcategory", new { @class = "form-control pxeSubcategoryDDL", @id = "pxeSubcategoryList" })
                        </td>
                        <td style="border-bottom:none !important;border-top:none !important;">
                           <input type="text" class="form-control pxeRowIndex" id="pxeIndexId" name="pxeRowIndexIds" value="0" readonly />
                        </td>
                        <td style="border-bottom:none !important;border-top:none !important">
                           <input type="text" class="form-control pxeConcatField" name="pxeRowConcatField" readonly />
                        </td>
                        <td style="border-bottom:none !important;border-top:none !important;">
                           <button type="button" id="addNewCategoryBtn" class="form-control btn btn-xs btn-default addNewCategory" onclick="addRowPXE('pxeTbody')" data-toggle="tooltip" title="Add">
                           <i class="fa fa-plus"></i>
                           </button>
                        </td>
                        <td style="border-bottom:none !important;border-top:none !important;display:none;">
                            <button type="button" id="removeNewCategoryBtn" class="form-control btn btn-xs btn-default removeNewCategory" data-toggle="tooltip" title="Remove">
                            <i class="fa fa-remove"></i>
                            </button>
                        </td>
                     </tr>
                  </tbody>
              </table>
          </div>
      </div>
    

    JAVASCRIPT

    <script>
       //cascading dropdown list inside dynamically added rows
       $("#pxeTable").on('change', '.pxeCategoryDDL', function () {
           var table = document.getElementById('pxeTbody');
           var rowCount = table.rows.length;
    
           var pxeSelectedCategory = $(this).val();
           var row = $(this).closest('tr');                            // get the row
           var pxeSubcatSelect = row.find('.pxeSubcategoryDDL');       // get the other select in the same row
           var pxeRowIndex = row.find('.pxeRowIndex');
    
           alert(rowCount);
           alert(pxeSelectedCategory);
           //alert(pxeSubcatSelect.innerHTML);
    
           //pxeSubcatSelect.attr('disabled', false);
           pxeSubcatSelect.empty();
           pxeRowIndex.val(rowCount);
    
           // make ajax call passing the pxeSelectedCategory to controller. And in the success callback, update the options of pxeSubcatSelect
           $.ajax({
               type: 'POST',
               url: '@Url.Action("GetPSESubcategories", "PSERegistry")',
               dataType: 'json',
               data: { pse_category_id: pxeSelectedCategory },
               success: function (subCategories) {
                   pxeSubcatSelect.append($('<option></option>').val('').text('Select Subcategory'));
                   $.each(subCategories, function (i, sub) {
                       pxeSubcatSelect.append('<option value ="' + sub.Value + '">' + sub.Text + '</option>');
                  })
               }
            });
            return false;
         });
    
         //sub category dropdown on change
         $("#pxeTable").on('change', '.pxeSubcategoryDDL', function () {
             var table = document.getElementById('pxeTbody');
             var rowCount = table.rows.length;
             var row = $(this).closest('tr');
    
             //get the selected values in each dropdown list
             var pxeCategory = row.find('.pxeCategoryDDL').val();
             var pxeSubcategory = row.find('.pxeSubcategoryDDL').val();
             var pxeRowIndex = row.find('.pxeRowIndex').val();
             var pxeConcatField = row.find('.pxeConcatField');
    
             //concatenate all values and store in hidden text field
             var pxeConcatData = pxeCategory + "," + pxeSubcategory + "," + pxeRowIndex;
             alert(pxeConcatData);
             pxeConcatField.val(pxeConcatData);
          });
    
    
          //remove added rows
          $(document).on("click", ".removeNewCategory", function ()     {                                      
              $(this).closest("tr").remove(); // closest used to remove the respective 'tr' in which I have my controls
          });
    
    
          //dynamically add row for multiple events
          function addRowPXE(table_id) {
            alert('new pxe row added');
            var table = document.getElementById(table_id);
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
            var colCount = table.rows[0].cells.length;
            alert(rowCount);
    
            $("#removeNewCategoryBtn").attr('display', 'block');
    
            for (var i = 0; i < colCount; i++) {
                var newcell = row.insertCell(i);
                newcell.innerHTML = table.rows[0].cells[i].innerHTML;
                newcell.childNodes[0].selectedIndex = 0;
    
                switch (newcell.childNodes[0].type) {
                   case "text":
                       newcell.childNodes[0].value = rowCount;
                       break;
                   case "select":
                       newcell.childNodes[0].selectedIndex = 0;
                       break;
                 }
               }
            };
        </script>
    

    【讨论】:

      猜你喜欢
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多