How do I implement a checkbox list in ASP.NET Core?

后端 未结 4 775
傲寒
傲寒 2021-01-30 13:20

I am looking to implement a checkboxlist in ASP.NET Core, but am facing some difficulties.

My ViewModel:

public class GroupIndexViewModel
{
    public          


        
4条回答
  •  囚心锁ツ
    2021-01-30 13:48

    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; 
    }
    

提交回复
热议问题