Invoke selected Checkbox values in View Edit

Asked

Viewed 121 times

2

I don’t know how to return the values selected in checkbox to the View.

Controller:

public ActionResult Editar(int? id)
{
    // acedendo a um conjunto de valores de uma classe
    ViewBag.Daylist = GetDias(null);
    return View(inscricao);
}

Auxiliary Method:

private MultiSelectList GetDias(string[] selectedValues)
{
    List<DiasSemana> Dias = new List<DiasSemana>()
    {
        new DiasSemana() { ID = 0, Dia= "Domingo" },
        new DiasSemana() { ID = 1, Dia= "Segunda-Feira" },
        new DiasSemana() { ID = 2, Dia= "Terça-Feira" },
        new DiasSemana() { ID = 3, Dia= "Quarta-Feira" },
        new DiasSemana() { ID = 4, Dia= "Quinta-Feira" },
        new DiasSemana() { ID = 5, Dia= "Sexta-Feira" },
        new DiasSemana() { ID = 6, Dia= "Sábado" },
    };
    return new MultiSelectList(Dias, "ID", "Dia", selectedValues);
}

View:

<div class="form-group">
    @Html.LabelFor(model => model.Dias_Preferencial, htmlAttributes: new { @class = "control-label col-md-2" })

    <div class="col-md-3">
        <input type="checkbox" id="allcheck" />
        @Html.Label("Todos", new { @class = "control-label" })  <br />
        @foreach (var item in (MultiSelectList)ViewBag.Daylist)
        {                                
            <input type="checkbox" name="SelectDias" value="@item.Text" class="checkbox-inline" />
            @Html.Label(item.Text, new { @class = "control-label" })
            <br />
        }
    </div>
</div>
  • You are putting an equal name for all checkboxes, so in your model you should receive "Selectdias"

  • I didn’t get it, you could show me?

  • I’m sorry.. If I understand you right now, reread, you need to popular your drop with the right auxiliary method values? if so, create an Enum and direct it to the DROPDOWNLIST in this way.... @Html.DropDownList("MyType", &#xA; Html.GetEnumSelectList(typeof(MyType)) , &#xA; "Select My Type", &#xA; new { @class = "form-control" })

  • Any doubt, please follow the [http://stackoverflow.com/questions/388483/how-do-you-create-a-dropdownlist-from-an-enum-in-asp-net-mvc]

  • This is not a Dropdownlist, but a Checkbox list.

  • Sorry... http://stackoverflow.com/questions/11904410/populate-and-retrieve-data-in-checkbox-list-on-mvc3

Show 1 more comment

1 answer

0

This is the bad way to do it. The right way involves using @Html.ListBox or @Html.ListBoxFor:

@Html.ListBoxFor(m => m.SelectDias, (MultiSelectList)ViewBag.Daylist)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.