【问题标题】:How can I add Selected attribute with the the drop down list item如何使用下拉列表项添加 Selected 属性
【发布时间】:2021-01-03 17:34:30
【问题描述】:

我有以下记录,我正在尝试从记录中创建级联下拉列表。它工作正常,但如果数据项已选择 = true,我如何添加选定的属性。我有以下记录。如何添加有条件选择的属性 如果 item.IsSelected , Selected = IsSelected。

public IEnumerable<Category> GetCategories()
    {
        return new List<Category>
        {
            new Category { CategoryId = 1, CategoryName="Category 1" },
            new Category { CategoryId = 2, CategoryName="Category 2" },
            new Category { CategoryId = 3, CategoryName="Category 3" }
        };
    }
    public IEnumerable<SubCategory> GetSubCategories(int categoryId)
    {
        var subCategories = new List<SubCategory> {
            new SubCategory { SubCategoryId = 1, CategoryId = 1, SubCategoryName="SubCategory 1", IsSelected=false},
            new SubCategory { SubCategoryId = 2, CategoryId = 2, SubCategoryName="SubCategory 2" IsSelected= false },
            new SubCategory { SubCategoryId = 3, CategoryId = 3, SubCategoryName="SubCategory 3" IsSelected= true},
            new SubCategory { SubCategoryId = 4, CategoryId = 1, SubCategoryName="SubCategory 4" IsSelected= false},
             
        };
        return subCategories.Where(s => s.CategoryId == categoryId);
    }

@section scripts{ 
<script>
    $(function () {
        $("#CategoryId").on("change", function() {
            var categoryId = $(this).val();
            $("#SubCategoryId").empty();
            $("#SubCategoryId").append("<option value=''>Select SubCategory</option>");
            $.getJSON(`?handler=SubCategories&categoryId=${categoryId}`, (data) => {
                $.each(data, function (i, item) {
                    $("#SubCategoryId").append(`<option value="${item.subCategoryId}">${item.subCategoryName}</option>`);
                });
            });
        });
    });
</script>
}

【问题讨论】:

    标签: html asp.net-core cascadingdropdown


    【解决方案1】:

    如果 item.IsSelected ,我如何添加有条件选择的属性, 已选择 = 已选择。

    试试这个代码:

     $.each(data, function (i, item) {
             $("#SubCategoryId").append(`<option value="${item.subCategoryId}" 
                ${item.isSelected ? "Selected" : ""}>${item.subCategoryName}</option>`);
         });
    

    这是测试结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      • 2015-06-24
      • 1970-01-01
      相关资源
      最近更新 更多