I am looking to implement a checkboxlist in ASP.NET Core, but am facing some difficulties.
My ViewModel:
public class GroupIndexViewModel
{
public
Building on @dotnetstep's answer, I created a Tag Helper that takes a model of IEnumerable of SelectListItem and generates the fields described in his answer.
Here is the Tag Helper code:
[HtmlTargetElement(Attributes = "asp-checklistbox, asp-modelname")]
public class CheckListBoxTagHelper : TagHelper
{
[HtmlAttributeName("asp-checklistbox")]
public IEnumerable Items { get; set; }
[HtmlAttributeName("asp-modelname")]
public string ModelName { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var i = 0;
foreach (var item in Items)
{
var selected = item.Selected ? @"checked=""checked""" : "";
var disabled = item.Disabled ? @"disabled=""disabled""" : "";
var html = $@"";
html += $@"";
html += $@"";
output.Content.AppendHtml(html);
i++;
}
output.Attributes.SetAttribute("class", "th-chklstbx");
}
}
You will need to add the following to the _ViewImports.cshtml file:
@addTagHelper *,
Then to drop the check list box into your razor view it's as easy as:
You might notice that I'm adding a class attribute to the div to style the box and it's content. Here is the CSS:
.th-chklstbx {
border: 1px solid #ccc;
padding: 10px 15px;
-webkit-border-radius: 5px ;
-moz-border-radius: 5px ;
-ms-border-radius: 5px ;
border-radius: 5px ;
}
.th-chklstbx label {
display: block;
margin-bottom: 10px;
}