How to get dynamic checkBox values in the ASP.NET MVC controller

2

I made a view that relates the role of the user to the user, created the view with the dynamic check boxes that can register roles and then assign it to the user, only when sending the marked roles, in the controller does not return to the controller , it marks me null, these are my classes.

public class CheckBoxClass
{
    public string Nombre_ChB { get; set; }
    public bool Value_Check { get; set; }
    public int Id_Check { get; set; }
    public string IdUsuario { get; set; }
}


public class CheckBoxList
{
  public List<CheckBoxClass> CheckBoxLista { get; set; }
}


    public ActionResult ListaCheckVistaParcial(string ID)
    {
        using (var db = new ProductoEntities())
        {
            var q= db.USUARIO_INTERFACEMTY.Where(x => x.USERID == ID).FirstOrDefault();

            return View(ListaCheckBox(q));
        }


 public List<CheckBoxList> ListaCheckBox(USUARIO_INTERFACEMTY usuario)
    {
        List<CheckBoxList> listaChB = new List<CheckBoxList>();
        List<CheckBoxClass> lcbc = new List<CheckBoxClass>();
        CheckBoxClass lb;

        using (var db = new ProductoEntities())
        {
            foreach (ROL_ACCESO r in db.ROL_ACCESO)
            {
                lb = new CheckBoxClass();
                lb.Id_Check = Convert.ToInt32(r.ID);
                lb.Nombre_ChB = r.NOMBRE_ROL;
                lb.Value_Check = false;
                lb.IdUsuario = usuario.USERID;
                lcbc.Add(lb);
                listaChB.Add(new CheckBoxList() { CheckBoxLista = lcbc });
            };
        }

        return listaChB;
    }


[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ListaCheckVistaParcial(CheckBoxList cb)
    {

        return RedirectToAction("Index", "Account");
    }

@model IEnumerable< InterfaceMonterrey.Models.CheckBoxList>

@{
    ViewBag.Title = "ListaCheckVistaParcial";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>ListaCheckVistaParcial</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Asignar Rol</h4>
        <hr />
 
        @{
            int i = 0;
        }
        @foreach (var item in Model)
        {
            if(i <= Model.Count())
            {
                <div class="form-group">
                @Html.Label(item.CheckBoxLista[i].Nombre_ChB, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.CheckBoxFor(model => item.CheckBoxLista[i].Value_Check)
                        @Html.ValidationMessageFor(model => item.CheckBoxLista[i].Value_Check, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
                i++;
            } 
        }

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

    
asked by andres martinez 05.09.2018 в 19:22
source

1 answer

0

When you generate the checkboxes they are generated in the following way:

<input type="checkbox" value="" name="Value_Check"/>
<input type="checkbox" value="" name="Value_Check" />
//...

As you will notice, all are generated with the same name. If you look for the value Value_Check in the controller, you will notice how the value of the last selected check will return to you:

//...
public PartialView ListaCheckVistaParcial(CheckboxList list)
{
   string value = Request["Value_Check"];
  //...
}
//..

In order to send multiple values with the same name, you have to indicate the name as if it were an array:

<input type="checkbox" name="Value_Check[]" />
<input type="checkbox" name="Value_Check[]" />

In your case it would be:

 @Html.CheckBoxFor(model => item.CheckBoxLista[i].Value_Check, attributes: new { name = "Value_Check[]"})

Then the action separates the values since they are sent separated by a comma:

//...
public PartialView ListaCheckVistaParcial(CheckboxList list)
{
   string[] values = Request["Value_Check[]"].Split(',');
  //...
}
//..

Request["Value_Check[]"] will return the values of the selected checkbox. For example if you select 3 checkbox, it will return you: True, True, True .

That said, it is obvious that you will have problems to be able to identify which value belongs to which checkbox so you will have to invent a mechanism to identify what value belongs to which checkbox.

    
answered by 06.09.2018 / 14:54
source