If you want to pass a selected brandId to an action using ajax and have the action return a list to set select options in javascript, you can follow this example:
Model:
public class Product
{
public int BrandId { get; set; }
public int ProductId { get; set; }
}
Controller (Using fake data for testing):
[HttpGet]
public IActionResult TestProduct() {
ViewBag.BrandId = new List<SelectListItem> { new SelectListItem { Text = "brand1", Value = "1" }, new SelectListItem { Text = "brand2", Value = "2" }, new SelectListItem { Text = "brand3", Value = "3" } };
ViewBag.ProductId = new List<SelectListItem> { new SelectListItem { Text = "select product", Value = "" } };
return View();
}
[HttpPost]
public List<SelectListItem> TestProduct(int BrandId)
{
List<SelectListItem> l = new List<SelectListItem> { new SelectListItem { Text = "product1", Value = "1" }, new SelectListItem { Text = "product2", Value = "2" }, new SelectListItem { Text = "product3", Value = "3" } };
return l;
}
View:
@model xxx.xxx.Product
<select asp-for="BrandId" asp-items="ViewBag.BrandId" id="transactionBrand" onchange="brandSelect()"></select>
<select asp-for="ProductId" asp-items="ViewBag.ProductId" id="transactionProduct"></select>
@section scripts{
<script>
function brandSelect() {
$.ajax({
type: "POST",
data: { BrandId: $("#transactionBrand").val() },
url: 'TestProduct',
}).done(function (data) {
var items = '';
$("#transactionProduct").empty();
$.each(data, function (index, Product) {
items += "<option value='" + Product.value + "'>" + Product.text + "</option>";
});
$('#transactionProduct').html(items);
})
}
</script>
}
Result:
https://i.sstatic.net/5wbH9.gif