DreamBig
DreamBig

Reputation: 69

Get multiple checked checkbox values in MVC controller

My code is below:

On page i have a products list with checkbox, code & name of that product. When selecting multiple checkboxes, on submit click, i need to get the selected checkbox values & save it in the DB.

Product View Model class:

public class ProductVM
{
 public ProductVM()
    {
        this.ProductsList = new List<Product>();
    }

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

public class Product
{
    public bool IsSelected { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

}

Product Controller:

[HttpGet]
public ActionResult Edit()
{
var model = new ProductVM();

        var product1 =  new ProductVM.Product
            {
                Code = "Product1",
                Name = "Apple"
            };


        var product2 =  new ProductVM.Product 
            {
                Code = "Product2",
                Name = "Banana"
            };

        model.ProductsList.Add(Product1);
        model.ProductsList.Add(Product2);

        return View(model);
     }

[HttpPost]
public ActionResult Edit(ProductVM model)
{
if (model.ProductsList.Any(m => m.Selected))  
        {
           //How to get the selected Code & Name here
        }
}

Product View:

@model ProductVM
@using(Html.BeginForm())
{
   foreach (var item in Model.ProductsList)
   {
        @Html.CheckBox("IsSelected", item.IsSelected) 
        @Html.Label(item.Code)
        @Html.Label(item.Name)
   }
   <input type="submit" />
 }

Upvotes: 1

Views: 23573

Answers (2)

fly_ua
fly_ua

Reputation: 1054

To demo my code from my comment to question- You can get idea from it

@foreach (var item in ViewBag.FocusesList)
{
    <label>
        <input type="checkbox" value="@item.ConfigurationId" name="FocusList" id="FocusList" /> @item.Value.Name
    </label>
}

After submit you have all checked values split by comma in Request["FocusList"]

Upvotes: 2

Chris Pratt
Chris Pratt

Reputation: 239440

First, you need to use for instead of foreach. Otherwise Razor won't generate the proper field names. Second, you need hidden inputs for the Code and Name properties so these will get posted back:

for (var i = 0; i < Model.ProductsList.Count(); i++)
{
    @Html.HiddenFor(m => m.ProductsList[i].Code)
    @Html.HiddenFor(m => m.ProductsList[i].Name)
    <label>
        @Html.CheckBoxFor(m => m.ProductsList[i].IsSelected)
        @Html.DisplayFor(m => m.ProductsList[i].Code)
        @Html.DisplayFor(m => m.ProductsList[i].Name)
    </label>
}

Upvotes: 2

Related Questions