You want to save the days of the week selected by the user, saving the contents of the label as a string.
What comes to the controller when I select all checkBox
Domingo false
Segunda-Feira false
Terça-Feira false
Quarta-Feira
I wanted to save the label text of the checkbox in my database as a string
, and discard the "fake."
Controller:
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-Feira" },
};
return new MultiSelectList(Dias, "ID", "Dia", selectedValues);
}
Get:
public ActionResult CriarGrupo()
{
// acedendo a um conjunto de valores de uma classe
ViewBag.Daylist = GetDias(null);
return View();
}
Post:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CriarGrupo([Bind(Include = "GrupoID,AnoPastoral,HoraInicio,DiaSessao,AnoCatequese,LetraGrupo,Sala,Observacoes")] Grupo grupo, params string[] SelectDias)
{
grupo.DiaSessao = SelectDias[0] + SelectDias[1] + SelectDias[2] + SelectDias[3] + SelectDias[4] + SelectDias[5] + SelectDias[6];
if (ModelState.IsValid)
{
db.Grupo.Add(grupo);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(grupo);
}
View:
<div class="form-group">
@Html.LabelFor(model => model.DiaSessao, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-3">
@foreach (var item in (MultiSelectList)ViewBag.Daylist)
{
// @Html.CheckBox("SelectDias", new { @class = "checkbox-inline", @value = @item.Text })
<input type="checkbox" name="SelectDias" value="@item.Text" class="checkbox-inline" />
@Html.Label(item.Text, new { @class = "control-label" })
<br />
}
</div>
</div>