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.

1
  • would you choose the answer or comment on them? Commented Jun 17, 2012 at 19:36

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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>

3 Comments

Can you change IEnumerable to IList?
IList on UI is a bad practice. It should be only IEnumerable<T>.
Program manager for the ASP.NET MVC is using IList<T> in his examples. Model Binding To A List
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

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.