如何在下拉列表项中添加Selected属性

问题描述

我有以下记录,并且我试图从该记录中创建级联下拉列表。它工作正常,但是如果数据项的selected = true,如何添加选定的属性我有以下记录。如何添加有条件选择的属性 如果是item.IsSelected,则选择的= 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,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>
}

解决方法

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

只需尝试以下代码:

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

这是测试结果:

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...