Displaying a multi-column checkbox list

2019-06-25 04:34发布

问题:

I'm currently displaying my list of checkboxes like this:

foreach (var employee in Model.Employees) {        
    @Html.CheckBox(employee.Name);<br />   
}

This is great if you want one long column of checkboxes, but my list is getting long, so I want to display it in 2 or 3 columns.

Is there an easy way to do this? I know I can create a table, then put in a for loop for the first half of the Employees for one column, and then another for loop for the other half of the Employees in another column. But that seems so primitive, there has to be a simpler, cleaner way.

回答1:

I would use 2 or 3 html lists containing your checkboxes, each list appearing immediately after the next in the markup, and use css to float each list to the left.

This example will separate checkboxes in to 2 lists if there are more than 10 checkboxes:

CSS:

.multi-list 
{
    float: left;
    padding-right: 50px;
}

.clear
{
    clear: both;
}

HTML markup w/ Razor:

@{
    if (Model != null)
    {
        int itemCount = 0;        
        <ul class="multi-list">
            @foreach (var item in Model) {
                itemCount++;
                <li>
                    @Html.DisplayFor(modelItem => item.Name)
                    @Html.CheckBoxFor(modelItem => item.Active)
                </li>
                if (Model.Count() > 10 && itemCount == (int)(Model.Count() / 2))
                {
                    @Html.Raw("</ul><ul class=\"multi-list\">");
                }
            }
        </ul>
        <div class="clear"></div>
    }
}