12

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

3
  • Please show your view
    – chamara
    Jun 11, 2013 at 6:06
  • Did you try @Html.CheckBoxFor
    – Roger Far
    Jun 11, 2013 at 6:21
  • @Rogier21 - how will i write in this context ? Jun 11, 2013 at 6:29

5 Answers 5

23

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.

2
  • It was awesome :)
    – MJ X
    Dec 16, 2016 at 19:05
  • Thanks big 🐕. I just couldn't get the View-Model items setup right. I had the name of the checkboxes with the '[]' suffix on them. Once I removed those, and ensured the Model's property was a string array, it worked.
    – clamum
    May 1 at 17:58
9

Try this:

@Html.HiddenFor(m => Model.pColors[i].Value);
@Html.HiddenFor(m => Model.pColors[i].Text);
@Html.CheckBoxFor(m => Model.pColors[i].Selected);
8
  • it worked for me , now able to take number of selected checkboxes :) but one more question will help please ? Jun 11, 2013 at 6:52
  • i have model properties which are of bit datatype. i want to put checkbox for that and get on post method. i have done this code :<tr> <td> Jewish </td> <td> @Html.CheckBox("Jewish", new { id = "chkJewish" }) @Html.ValidationMessageFor(model => model.SKUs.Jewish) </td> </tr> but on post not getting weather its selected or not.. Jun 11, 2013 at 6:56
  • try same here @Html.CheckBoxFor(model.SKUs.Jewish, new { id = "chkJewish" })
    – karaxuna
    Jun 11, 2013 at 7:05
  • i tried this : @Html.CheckBoxFor(model => model.SKUs.Jewish, new { id = "chkJewish" }) gives error that cant convert bool? to bool Jun 11, 2013 at 7:08
  • Then try this: @Html.CheckBox("SKUs.Jewish", (bool)Model.SKUs.Jewish, new { id = "chkJewish" })
    – karaxuna
    Jun 11, 2013 at 7:12
2

Me too was having a scenario like you and I implemented it using EditorFor by referring this link "ASP.NET MVC - Multiple checkboxes for row selection in HTML table"

For that you need create a EditorTemplate folder and need to add the view with a same name of model. View code like below

@model EditorForSample.Models.ProductViewModel


<tr>
  <td class="text-nowrap">@Html.CheckBoxFor(m => m.Selected, new {@class="chkSelect"})  </td>
<td colspan="3">
    @Model.Name
    @Html.HiddenFor(m => m.Name)
</td>
<td>
    @Model.Price
    @Html.HiddenFor(m => m.Price)
</td>

Model can be like below.

public class ProductPageViewModel
{
    public string Message { get; set; }

    public List<ProductViewModel> ProductsList { get; set; }
}

public class ProductViewModel
{
    public bool Selected{ get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
}

And in parent view you can write html like below

 .......
  <div class="col-md-12">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th><input type="checkbox" id="chkSelectAll" /></th>
                    <th colspan="3">
                        Product Name
                    </th>
                    <th>
                        Cost
                    </th>

                </tr>
            </thead>
            <tbody>
                @Html.EditorFor(m => m.ProductsList)
            </tbody>
        </table>
    </div>
.........

Above link has sample project too. I know answer of this question is already accepted but just sharing this. It may help someone. Thanks :-)

1

<script>
   $("#btndownloading").click(function (e) {
                var ckebox_value = $("input[name=cmmdLabels]:checked").map(function () {
                    if ($(this).val() != 0) {
                        return $(this).val();
                    }
                }).get();
                var ckeck_box_length = ckebox_value.length;
                if (ckeck_box_length != 0) {
                    $.ajax({
                        url: '@Url.Action("dowloadingfile", "dowloading")',
                        type: "POST",
                        data: JSON.stringify({ selectionvalue_ck: ckebox_value }),
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {

                        }, 
                        }
                    });
                }
                else {
                    alert("Please select at least one File");
                }
            });
</script>

 [HttpPost]
        public ActionResult dowloadingfile(string[] selectionvalue_ck)
        {
			string fileName = "";
			for (int j = 0; j < selectionvalue.Length; j++)
                {
					fileName = selectionvalue_ck[j];
				}
		}
<input class="cb-element" name="cmmdLabels" value="1.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="2.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="3.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="4.txt" type="checkbox">
<input class="cb-element" name="cmmdLabels" value="5.txt" type="checkbox">

<button id="btndownloading">Download file</button>

1
  • 1
    Have in mind that answers which contain only code are not considered complete. Aug 8, 2018 at 9:07
0

I use this extension:

public static MvcHtmlString CheckBoxListFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, IEnumerable<TProperty>>> expression,
    IEnumerable<SelectListItem> multiSelectList,
    Object htmlAttributes = null)
{
    // Derive property name for checkbox name
    var body = expression.Body as MemberExpression;
    if (body == null)
        return null;

    String propertyName = body.Member.Name;

    // Get currently select values from the ViewData model
    IEnumerable<TProperty> list = expression.Compile().Invoke(htmlHelper.ViewData.Model);

    // Convert selected value list to a List<String> for easy manipulation
    var selectedValues = new List<String>();

    if (list != null)
        selectedValues = new List<TProperty>(list).ConvertAll(i => i.ToString());

    // Create div
    var ulTag = new TagBuilder("ul");
    ulTag.AddCssClass("checkBoxList");
    ulTag.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);

    // Add checkboxes
    foreach (var item in multiSelectList)
    {
        ulTag.InnerHtml += String.Format(
            "<li><input type=\"checkbox\" name=\"{0}\" id=\"{0}_{1}\" value=\"{1}\" {2} /><label for=\"{0}_{1}\">{3}</label></li>",
            propertyName,
            item.Value,
            selectedValues.Contains(item.Value) ? "checked=\"checked\"" : "",
            item.Text);
    }

    return MvcHtmlString.Create(ulTag.ToString());
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.