0
@model IEnumerable<FacetValue>
<ul>
    @foreach (var association in Model)
    {
        <li>

            **@Html.CheckBox("association",association.IsSelected) @Html.Label("association", association.Text)**

            @if (association.IsSelected == true)
            {
                <input type="checkbox" id="association" class="left" value="@association.Text" checked="checked"/>
            }
            else
            {
                <input type="checkbox" id="association" class="left" value="@association.Text"/>
            }
            <label>@association.Text</label>
        </li> 
    }
</ul>

I am using the code that starts with @if vs the @htmlCheckBox. 1. The layout is messed up 2. It doesn't display is messed up and displays check box in one place and text in another place. 3. a hidden value is generated for every check box.

Now the question is how can I display the the contents how I want without the @if else logic.

VolleyBall Player
  • 710
  • 3
  • 11
  • 27

3 Answers3

2

To bind complex objects, we need to provide an index for each item to insure correct postback. That's why we need to change IEnumerable<> to IList<> (or you can created another variable and populated it with Model.ToList()). Than we need to change foreach() to for(), so Html.CheckBoxFor can correctly create IDs and NAMEs that will insure correct postback.

@model IList<FacetValue>
<ul>
    @for (int i = 0; i < Model.Count(); i++)
    {
        <li>
            @Html.LabelFor(model => model.Model[i].IsSelected, Model[i].Text)
            @Html.CheckBoxFor(model => model.Model[i].IsSelected)
        </li> 
    }
</ul>
Aleksey Cherenkov
  • 1,405
  • 21
  • 25
2

There is no need to reinvent the wheel. Here is a very good post to look: Asp.net MVC Multiple check-boxes in an array

If it still does not cover your scenario then look at this pre-existing discussions:

Discussion 1, Discussion 2

Community
  • 1
  • 1
Yusubov
  • 5,815
  • 9
  • 32
  • 69
0

you can customize your extension method of Check box with property additional Visible, and in the creating of checkbox , you pass the value of visible

Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51