I have the following Record, and from the record I am trying to create the cascade dropdown. It is working fine but how can I add the selected attribute if the data item has selected = true. I have the following record. How can I add conditionally selected attribute if 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>
}
How can I add conditionally selected attribute if item.IsSelected , Selected = IsSelected.
Just try this code:
$.each(data, function (i, item) {
$("#SubCategoryId").append(`<option value="${item.subCategoryId}"
${item.isSelected ? "Selected" : ""}>${item.subCategoryName}</option>`);
});
Here is the test result: