How to draw a checkbox in razor MVC3

@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.

Answers


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


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>

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


Need Your Help

gridview datasource issue

c# asp.net web-services

I am calling a webservice as follows.I have to display name, description and url in the gridview using this webservice.

@OneToMany without inverse relationship and without a join table?

java hibernate orm jpa one-to-many

This is a similar problem to "Hibernate @OneToMany without a separate join table", in that I need a @OneToMany relationship without a join table. However, I would also like to not define the inverse