Asp.NET MVC bind checkbox list with string value

1

I have a list of checkboxes and I need to bind values that are strings (@ item.SelectedValue) with my IEnumerable>.

 <div class="editor-field perfil-filtro-expander-todasAcoes">
        <div class="metro perfil-filtro-expander-overflow todasAcoes" id="todasAcoes" name="todasAcoes">
            @foreach (DetailedLookupModel<string> item in (IEnumerable<DetailedLookupModel<string>>)ViewBag.Acoes)
            {                    
                <div style="padding-bottom: 10px;">
                    @*<input id="@item.SelectedValue" type="checkbox" name="@item" value="@item.SelectedValue"/>*@
                    @Html.TextBoxFor(x => Model.Acoes, new { @type = "checkbox", @id = item.SelectedValue, @value = item.SelectedValue})
                    <label for="@item.SelectedValue">
                        <b>@item.Title</b>
                        <br />
                        <span class="perfil-filtro-expander-descricao">
                            @item.Description
                        </span>
                    </label>
                </div>
            }
        </div>
        @Html.ValidationMessageFor(model => model.Descricao)
    </div>

Model Property:

[DisplayName("Ações")]
[Required]
public IEnumerable<DetailedLookupModel<String>> Acoes { get; set; }

In this way I can get the checboxes, but the value of them that was to be "value" comes with null . Also I can not make changes to the labels, as my css depends on those ids to understand what the labels are for the appropriate fields.

    
asked by anonymous 21.08.2015 / 17:17

1 answer

2

This is a classic case of BeginCollectionItem .

Do the following:

<div class="editor-field perfil-filtro-expander-todasAcoes">
    <div class="metro perfil-filtro-expander-overflow todasAcoes" id="todasAcoes" name="todasAcoes">
        @foreach (DetailedLookupModel<string> item in (IEnumerable<DetailedLookupModel<string>>)ViewBag.Acoes)
        {                    
            @Html.Partial("_Acoes", item)
        }
    </div>
    @Html.ValidationMessageFor(model => model.Descricao)
</div>

_Acoes.cshtml

@model DetailedLookupModel<String>

@using (Html.BeginCollectionItem("Acoes"))
{
    <div style="padding-bottom: 10px;">
                @Html.TextBoxFor(x => Model.Acoes, new { @type = "checkbox", @id = item.SelectedValue, @value = item.SelectedValue})
                <label for="@item.SelectedValue">
                    <b>@item.Title</b>
                    <br />
                    <span class="perfil-filtro-expander-descricao">
                        @item.Description
                    </span>
                </label>
        </div>
}
    
21.08.2015 / 21:05