问题描述
我有以下记录,并且我试图从该记录中创建级联下拉列表。它工作正常,但是如果数据项的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>
}