Get list of checkboxes in the controller in Asp.Net

2

How do I get a list of checkboxes like this:

<div class="editor-field" style="overflow-y: auto; height: 150px;">
<label>Especializações:</label>
@{
    if (ViewBag.ListProfessionalSpecialization != null)
    {
        foreach (ProfessionalSpecialization item in (List<ProfessionalSpecialization>)ViewBag.ListProfessionalSpecialization)
        {
            <label style="display: inline">
                <input type="checkbox" Value="@item.IdProfessionalSpecialization" name="ProfessionalSpecialization">
                @Html.DisplayFor(modelItem => item.Title)
            </label>
        }
    }
    else
    {
        <label>O sistema não possue uma Especialização cadastrada. Finalize o cadastro e adicione uma nova especialização no seu painel de controle.</label>
    }
}
</div>

I need to get the controller and save the values in a table N to N. I need to save by ID.

My controller is as follows:

public ActionResult Create(FormCollection form)
{
    var pUser = new ProfessionalUser()
    {
        IdProfessionalType = 1, //buscar o id na view
        IdProfessionalSpecialization = 1, //buscar o id na view
        IdProfessionalRegister = Convert.ToInt32(form["register"]),
        Name = form["name"],
        Password = form["password"],
        Email = form["email"],
        Phone = Convert.ToInt32(form["phone"]),
        City = form["city"],
        State = form["state"]                
    };

    if (ModelState.IsValid)
    {
        using (ProfessionalUserDAO dao = new ProfessionalUserDAO())
        {
            if (dao.SaveProfessionalUser(pUser))
            {
                ViewBag.AlertMessage = "Profissional salvo com sucesso!";
                return View();
            }
        }
    }

    ViewBag.AlertMessage = "Ocorreu um problema ao salvar!";
    return View(pUser);
}
    
asked by anonymous 12.05.2014 / 19:25

1 answer

3

This is more complicated because everything has to be done manually.

The best way is to use the excellent HtmlHelper , which has Razor methods to assemble the sequence of fields. In the example below, I use a DropDownListFor :

@Html.DropDownListFor(model => model.IdProfessionalSpecialization, ((IEnumerable<ProfessionalSpecialization>)ViewBag.ListProfessionalSpecialization).Select(option => new SelectListItem
{
    Text = option.Title,
    Value = option.IdProfessionalSpecialization.ToString(),
    Selected = (Model != null) && (option.IdProfessionalSpecialization == Model.IdProfessionalSpecialization)
}), "Selecione...")

For CheckBoxList , the component is MvcCheckBoxList : link

Here are examples of usage:

link

Using the template annotated as @model in your View to send to Controller . It would look like this:

public ActionResult Create(ManyLife.ASP.Models.ProfessionalUser professionalUser)
    {
        // Como o objeto vem pronto da View, não é necessário montá-lo, então
        // comentei o código.
        /* var pUser = new ProfessionalUser()
        {                
            IdProfessionalType = 1, //buscar o id na view
            IdProfessionalSpecialization = 1, //buscar o id na view
            IdProfessionalRegister = Convert.ToInt32(form["register"]),
            Name = form["name"],
            Password = form["password"],
            Email = form["email"],
            Phone = Convert.ToInt32(form["phone"]),
            City = form["city"],
            State = form["state"]                
        }; */

        if (ModelState.IsValid)
        {
            using (ProfessionalUserDAO dao = new ProfessionalUserDAO())
            {
                if (dao.SaveProfessionalUser(professionalUser))
                {
                    ViewBag.AlertMessage = "Profissional salvo com sucesso!";
                    return View();
                }
            }
        }

        ViewBag.AlertMessage = "Ocorreu um problema ao salvar!";

        // Remonte aqui o ViewBag.ProfessionalSpecialization
        // ViewBag.ProfessionalSpecialization = trazerDadosDaSuaDao

        return View(professionalUser);
    }

But as in this case you have to mount a list of options to popular your CheckBoxList , it would be advisable to create a ViewModel to meet all Helper parameters.

It would look like this:

@Html.CheckBoxListFor(x => x.PostedProfessionalSpecializations.ProfessionalSpecializationsIDs,  
                  x => x.AvailableProfessionalSpecializations,       // List<ProfessionalSpecialization>()
                  x => x.Id,                    // ProfessionalSpecialization.IdProfessionalSpecialization
                  x => x.Name,                  // ProfessionalSpecialization.Name
                  x => x.SelectedProfessionalSpecializations)        // List<ProfessionalSpecialization>() - Lista de especializações selecionadas

The ViewModel would look like this:

namespace ManyLife.ASP.ViewModels {
    public class ProfessionalUserViewModel {
        // Coloque aqui todos os campos que já existem no Model

        public IList<ProfessionalSpecialization> AvailableProfessionalSpecializations{ get; set; }
        public IList<ProfessionalSpecialization> SelectedProfessionalSpecializations{ get; set; }
        public PostedProfessionalSpecializations PostedProfessionalSpecializations { get; set; }
    }

    // Aqui é um array de strings, mas na verdade eles podem ser convertidos para inteiro
    // sem problema algum.
    public class PostedProfessionalSpecializations {
        public string[] ProfessionalSpecializationsIDs { get; set; }
    }
}

So the top View changes to:

@model ManyLife.ASP.ViewModels.ProfessionalUserViewModel

And Controller also changes:

public ActionResult Create(ManyLife.ASP.ViewModels.ProfessionalUser professionalUser) { ... }
    
12.05.2014 / 19:34