I want to create a checkbox using enum. I can create a simple checklist using enum without any issues, but it give me error for when I use asp-for="" in my checklist.
Whenever I use asp-for="", I get this error:
InvalidOperationException: Unexpected 'asp-for' expression result type 'Website.Data.Enum.CollectionCategory' for . 'asp-for' must be of type 'System.Boolean' or 'System.String' that can be parsed as a 'System.Boolean' if 'type' is 'checkbox'.
I have created radio buttons using enum with asp-for="" and it worked without any problem.
I searched online why that is the case and here is what I found:
Unfortunately, to Render Checkbox for each enum value is not possible – by definition you always only select one value of an enumeration. If you want checkboxes, you can make separate Boolean attributes for each checkbox.
I have searched for multiple solutions but unfortunately, my problem is still unresolved.
Here is my code:
Enum definition:
public enum CollectionCategory
{
[Display(Name = "Veg")]
Veg = 0,
[Display(Name = "NonVeg")]
NonVeg = 1,
[Display(Name = "Breakfast")]
Breakfast = 2,
[Display(Name = "Lunch")]
Lunch = 3,
[Display(Name = "Dinner")]
Dinner = 4
}
Model class:
public class Post
{
// Code Before
public CollectionCategory CollectionCategory { get; set; }
// Code After
}
View model:
public class CreatePostViewModel
{
// Code Before
public CollectionCategory CollectionCategory { get; set; }
}
Controller:
public IActionResult Create()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Create(CreatePostViewModel postVM)
{
if (ModelState.IsValid)
{
var post = new Post
{
// Code before
CollectionCategory = postVM.CollectionCategory,
};
_postInterface.Add(post);
return RedirectToAction("Index");
}
else
{
// Error
}
return View(postVM);
}
View (works fine without asp-for=""):
<div class="col-md-12 mb-3">
@foreach (var value in Enum.GetValues(typeof(CollectionCategory)))
{
<input type="checkbox" asp-for="CollectionCategory" class="btn-check" id="@value" value="@((int)value)" required>
<label asp-for="CollectionCategory" class="btn btn-outline-primary" for="@value">@value</label>
}
</div>
Thank you for your help.

selectbox then addmultipleattribute to it?