I try to make a form with category and subcategory which are all checkbox and use it to set my service categories and subcategories. I try some method like using SelectListItem but I couldn't use it for indented checkbox. this is my database diagram (I know it's not good, but the customer wanted it) : Services Diagram
My method to make a List of SelectListItem for Main and Sub categories:
public List<SelectListItem> GetAllMajorCategories()
{
return _context.CategoriesTbl
.Where(c => c.ParentId == null)
.Select(c => new SelectListItem
{
Value = c.CategoryId.ToString(),
Text = c.Title
}).ToList();
}
public List<SelectListItem> GetAllSubCategories()
{
return _context.CategoriesTbl
.Where(c => c.ParentId == c.CategoryId)
.Select(c => new SelectListItem
{
Value = c.ParentId.ToString(),
Text = c.Title
}).ToList();
}
Then I use these two method in my PageModel:
public void OnGet()
{
MainCategories = _serviceServices.GetAllMajorCategories();
SubCategories = _serviceServices.GetAllSubCategories();
}
Then in the Razorview I want to generate checkbox for every MajorCategory and it's SubCategories but I can't.
<div class="form-group">
@foreach (var item in Model.MainCategories)
{
<div class="icheckbox_minimal-blue">
<input type="checkbox" class="minimal" id="majorCat" name="majorCat" value="@item.Value">
<label> @item.Text </label>
</div>
}
</div>
How can I do that?
According to your comment , the GetAllSubCategories() method did return the wrong list,you just need to retutn CategoriesTbl's list when ParentId is not null.
Please refer to the following code for details:
PageModel.cs
public void OnGet()
{
MainCategories = GetAllMajorCategories();
SubCategories = GetAllSubCategories();
}
public List<SelectListItem> GetAllMajorCategories()
{
return _context.CategoriesTbl
.Where(c => c.ParentId == null)
.Select(c => new SelectListItem
{
Value = c.CategoryId.ToString(),
Text = c.Title
}).ToList();
}
public List<CategoriesTbl> GetAllSubCategories()
{
return _context.CategoriesTbl.Where(c => c.ParentId != null).ToList();
}
View:
@page
@model WebApplication1_rzaor_page.ShowCheckboxModel
@{
ViewData["Title"] = "ShowCheckbox";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>ShowCheckbox</h1>
<div class="form-group">
@foreach (var item in Model.MainCategories)
{
<div class="icheckbox_minimal-blue">
<input type="checkbox" class="minimal" id="majorCat" name="majorCat" value="@item.Value">
<label>@item.Text</label>
</div>
<ul>
@foreach (var subitem in Model.SubCategories.Where(x => x.ParentId == Convert.ToInt32(item.Value)).ToArray())
{
<li>
<input type="checkbox" class="minimal" id="subCat" name="subCat" value="@subitem.CategoryId">
<label>@subitem.Title</label>
</li>
}
</ul>
}
</div>
Here is the result :