Get list of checkboxes in the controller in Asp.Net

Asked

Viewed 1,367 times

2

How do I get a checkbox list 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 take the controller and save in the database 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);
}

1 answer

3


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

The best way is by using the excellent HtmlHelper, that 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...")

To CheckBoxList, the component is the MvcCheckBoxList: https://www.nuget.org/packages/MvcCheckBoxList/

Here are examples of use:

http://mvccbl.com/Examples

Using the annotated model as @model in his View to send to the Controller. 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 put together a list of options to popular your CheckBoxList, the recommended would be to create a ViewModel to meet all parameters of the Helper.

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; }
    }
}

Therefore, the top of the View mute to:

@model ManyLife.ASP.ViewModels.ProfessionalUserViewModel

And the Controller also changes:

public ActionResult Create(ManyLife.ASP.ViewModels.ProfessionalUser professionalUser) { ... }

Browser other questions tagged

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