4

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.

2
  • I don't see how using 2 or 3 columns would make the list any shorter. You would still get many checkboxes horizontally. Also grouping them in columns would make it less intuitive for the user if they don't have some logical meaning for being grouped. Commented Jul 7, 2011 at 20:58
  • There is an easier way to do this: stackoverflow.com/a/7448678/626533 Commented Oct 3, 2013 at 10:04

1 Answer 1

3

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>
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.