Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Multiple Selected checkboxes in MVC

i have a ProductController which is consists of Create method.

My Model :

public class ProductEntry
{
    public Crescent.LinqModel.Product Products { get; set; }
    public ProductSKU SKUs { get; set; }
    public List<SelectListItem> pColors { get; set; }

    public ProductEntry()
    {
        pColors = new List<SelectListItem>();
    }
}

Create Get Method :

    public ActionResult Create()
    {
        CrescentAdmin.Models.ProductEntry product = new CrescentAdmin.Models.ProductEntry();
        var colors = _appData.GetProductColors().ToList();
        for (int i = 0; i < colors.Count; i++)
        {
            if (i == 0)
                product.pColors.Add(new SelectListItem { Value = colors[i].Name.ToString(), Text = colors[i].Name, Selected = true });
            else
                product.pColors.Add(new SelectListItem { Value = colors[i].Name.ToString(), Text = colors[i].Name });
        }

        return View(product);
    }

this colors i want to fill in the list of checkboxes in which i can select multiple checkboxes.its working properly.

Create Post :

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult Create(CrescentAdmin.Models.ProductEntry entry, HttpPostedFileBase uploadFile)
    {
      //code to insert in two table
      // required to fetch which checkboxes are selected ??    
    }

Create View :

       @model CrescentAdmin.Models.ProductEntry

code to fill list of checkboxes :

         <tr>
            <td>
                Product Colors
            </td>
            <td>
                @if (Model.pColors != null && Model.pColors.Count > 0)
                {
                    for (int i = 0; i < Model.pColors.Count; i++)
                    {
                        //if (Model.pColors[i])
                        //{
                            <input type="checkbox" value="@Model.pColors[i].Value" id="@Model.pColors[i].Value"/> @Model.pColors[i].Text <br />
                             @Html.HiddenFor(m => Model.pColors[i].Value);
                             @Html.HiddenFor(m => Model.pColors[i].Text);
                             @Html.HiddenFor(m => Model.pColors[i].Selected);
                        //}
                        //else
                        //{
                        //    <input type="checkbox" value="@Model.pColors[i].Value" /> @Model.productColors[i].Name <br />
                        //}
                    }
                }


                @Html.ValidationMessageFor(model => model.SKUs.ProductColors)
            </td>
        </tr>

i have tried this code , but no luck !!

required to fetch which checkboxes are selected ?? Please help

like image 618
DharaPPatel Avatar asked Jun 11 '13 06:06

DharaPPatel


2 Answers

I normally use below approach when dealing with checkboxes check whether it helps you.

Model:

namespace GateApplication.Models
{
    public class Gate
    {
        public string PreprationRequired { get; set; }
        public List<CheckBoxes>  lstPreprationRequired{ get; set; }
        public string[] CategoryIds { get; set; }
    }

    public class CheckBoxes
    {
        public int ID { get; set; }
        public string Value { get; set; }
        public string Text { get; set; }
        public bool Checked { get; set; }
    }
}

Controller:

Load CheckBox Value:

public ActionResult Create()
   {
      List<CheckBoxes> lstchk = new List<CheckBoxes>()
            {
                new CheckBoxes {Text="coduit", Value="coduit" },
                new CheckBoxes {Text="safety", Value="safety" },
                new CheckBoxes {Text="power", Value="power" },
                new CheckBoxes {Text="access", Value="access" }
            };

          var model = new Gate
            {
               lstPreprationRequired=lstchk
            };

            return View(model);
   }

View:

@foreach (var item in Model.lstPreprationRequired)
    {
        <input type="checkbox" id="@item.Value" name="CategoryIds" value="@item.Text"/>
                  <label for="optionId">@item.Text</label>
       <br />
    }

Now your view shold have list of checkboxes. Now saving CheckBox values to the database.

    [HttpPost]
    public ActionResult Create(FormCollection collection)
    {
        try
        {

            Gate gate = new Gate();
            TryUpdateModel(gate);

            if (ModelState.IsValid)
            {
                gate.PreprationRequired = Request.Form["CategoryIds"];// here you'll get a string containing a list of checked values of the checkbox list separated by commas

                if (string.IsNullOrEmpty(gate.PreprationRequired))//this is used when no checkbox is checked
                    gate.PreprationRequired = "None,None";

                Save();//Save to database
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }

        }
        catch
        {
            return View();
        }
    }

Now you have below kind of string in your database

safety,power,access

Now fetch the selected values and display the view.

public ActionResult Edit(int id)
        {
           List<CheckBoxes> lstchk = new List<CheckBoxes>()
            {
                new CheckBoxes {Text="coduit", Value="coduit" },
                new CheckBoxes {Text="safety", Value="safety" },
                new CheckBoxes {Text="power", Value="power" },
                new CheckBoxes {Text="access", Value="access" }
             };

            var model = new Gate
            {
                lstPreprationRequired =lstchk,
                CategoryIds = "safety,power,access".Split(',')//here get your comma separated list from database and assign it to the CategoryIds string array, i have used sample text for the values
            };

            return View(model);
        }

View:

  @foreach (var item in Model.lstPreprationRequired)
        {
             <input type="checkbox" id="@item.Value" name="CategoryIds" value="@item.Text" 
             @foreach (var c in Model.CategoryIds)
             {
               if(c == item.Value)
               {
                  <text> checked="checked"</text>
               }
             }/>
             <label for="optionId">@item.Text></label>
        }

Let me know if this does not help you.

like image 158
chamara Avatar answered Sep 22 '22 20:09

chamara


Try this:

@Html.HiddenFor(m => Model.pColors[i].Value);
@Html.HiddenFor(m => Model.pColors[i].Text);
@Html.CheckBoxFor(m => Model.pColors[i].Selected);
like image 38
karaxuna Avatar answered Sep 20 '22 20:09

karaxuna