I am trying to make a form using two drop-down select menus: one to select the category, the other to select a subcategory. I am trying to make it so the subcategory options are based on which category they select first.
This is my subcategory model :
public class SubCategory
{
[Key]
public int ID { get; set; }
[Required]
[StringLength(20)]
public string Name { get; set; }
[ForeignKey("Category")]
public int CatID { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Expense> Expenses { get; set; }
}
My controller:
public IActionResult Create()
{
//dropdown-category
var categoryList = (from category in _context.Categories
select new SelectListItem()
{
Text = category.Name,
Value = category.ID.ToString()
}).ToList();
categoryList.Insert(0, new SelectListItem()
{
Text = "----Select----",
Value = String.Empty
});
ViewBag.CategoryList = categoryList;
//dropdown-subcat
var subCategoryList = (from subCategory in _context.SubCategories
join category in _context.Categories
on subCategory.CatID equals category.ID
where subCategory.CatID == category.ID
select new SelectListItem()
{
Text = subCategory.Name,
Value= subCategory.ID.ToString()
}).ToList();
ViewBag.SubCategoryList = subCategoryList;
return View();
}
and my view:
<div class="form-group">
<label asp-for="CatID" class="control-label">Category</label>
<select asp-for="CatID"
class="form-control"
id="cID"
asp-items="@(new SelectList(ViewBag.CategoryList,"Value","Text"))">
</select>
<span asp-validation-for="CatID" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="SubCatID" class="control-label"> SubCategory </label>
<select asp-for="SubCatID"
class="form-control"
id="scID"
asp-items="@(new SelectList(ViewBag.SubCategoryList, "Value", "Text"))"></select>
<span asp-validation-for="SubCatID" class="text-danger"></span>
</div>
I know I might need some javascript to make this function. However, I'm not sure how to compare the category value with my local database.
Try to use ajax to compare category with subcategory table ,and return the data of all the subcategory.
<select asp-for="CatID"
class="form-control"
id="cID"
asp-items="@(new SelectList(ViewBag.CategoryList,"Value","Text"))" onchange="check(this)>
</select>
js:
function check(t) {
$.ajax({
type: "GET",
url: 'xxx?CatID=' + $(t).val(),
success: function (data) {
$.each(data, function (index, value) {
var text1 = '<option value=' + value.value + '>' +
value.text +'</option>';
$("#SubCatID").append(text1);
});
},
error: function (result) {
alert("error occured");
}
});
}
action:
public List<SelectListItem> xxx(int CatID){
//compare CatId with subcategory table here ,and return data of subcategorys
}