I working with cascading dropdowns in .NET Core. It works correctly using Ajax.
Here is the code:
<td>
<select id="productList" class="form-select" asp-items="@ViewBag.productItem">
</select>
</td>
<td>
<select id="colorId" >
</select>
</td>
//Ajax
$(document).ready(function () {
getProductByColor();
});
$("#productList").change(function () {
getProductByColor();
});
function getProductByColor() {
$.ajax({
url: '@Url.Action("GetProductByColor", "Invoice")',
type: 'GET',
data: {
id : $('#productList').val()
},
success: function (data) {
$('#colorId').empty();
$(data).each(function (index, item) {
$('#colorId').append('<option value="' + item.colorId + '">' + item.color.colorName + '</option>');
});
}
});
}
And the view of website will be like this:

But now I want show the Color Name not the Color Id. In my product items model, I have a Color property to navigate to Color model, so I can get the color name.
Here is the json return:
[
{
"productItemsId": 24,
"productId": 1,
"colorId": 1,
"productCode": "AF1-White",
"color": null,
"product": null,
"invoiceDetails": [],
"ordersDetails": [],
"productImages": [],
"productVariations": [],
"image1": null,
"image2": null,
"image3": null,
"image4": null
}
]
C# code:
public ProductItem()
{
}
public int ProductItemsId { get; set; }
public int ProductId { get; set; }
public int? ColorId { get; set; }
public string? ProductCode { get; set; }
public virtual Color? Color { get; set; }
I have tried to use the color property in Ajax but it didn't work
success: function (data) {
$('#colorId').empty();
$(data).each(function (index, item) {
$('#colorId').append('<option value="' + item.colorId + '">' + item.Color.colorName + '</option>');
});
}
Also use the include in GetColorByProduct method but still didn't work:
public JsonResult GetColorByProduct (int id)
{
return Json(_context.ProductItems.Where(n=>n.ProductItemsId == id)
.Include(n => n.Color)
.ToList());
}
Does anyone know the problem? I will appreciate any solutions. Many thanks