0

I am not not so familiar with MVC? Can anyone share pseudo code in MVC on how to implement checkboxes dynamically bind with a database table? This is how my table is defined, and this is the output that I am trying to get in the view.

Table - Produce
  ProduceID, Produce Name, Produce Type
    1             Banana        Fruit
    2             Apple         Fruit
    3             Okra          Vegetable
    4             Onion         Vegetable

View Output

Fruit
   checkbox Banana
   checkbox Apple
Vegetable
   Checkbox Okra 
   checkbox Onion

The selected values from the checkbox need to send to the controller.

Appreciate any help.

user749448
  • 189
  • 1
  • 5
  • 9

2 Answers2

0

If you are using Entity Framework then you can do something like below : //Create a view Model:

  public class ProductVM
  {
     string Produce_Name {get; set;}
     string Produce_Type {get; set;}
  }

//In your Data Access Layer : //It will fetch your data from the Table.

  public IEnumerable<ProductVM> GetAllProductList()
  {
    @using(DBContext context = new DBContext() ) 
    {
      return context.Produce.Select( p => new ProductVM () { Produce_Name = v.ProductName; Produce_Type = v.ProduceType;} ).ToList<>(ProductVM) ;
    }
  }

//Note in above code ProductType and ProductName refers to the Context Class Properties created by EF.

Now return this list to the View either in ViewBag or TempData as : // In Controller :

public ActionResult MyProduceAction()
{
  DAL dal = new DAL();
  var ProductList = dal.GetAllProductList();
  ViewBag.ProductList = ProductList;
  return View();
}

// In View access the ViewBag as follows:

 @{
    var ProductList = (IEnumerable<ProductVM>)ViewBag.ProductList;
  }


  @foreach(var p in ProductList)
  {
    @Html.CheckBox(p.Produce_Name, false, new { value = p.Produce_Type });
  }

Hope this helps.

Anand
  • 165
  • 3
  • 15
0

You could do something like this:

Controller

[HttpGet]
public ActionResult Products()
{
    List<ProductModel> products = GetProducts();
    return View(products);
}

[HttpPost]
public AcionResult Products(List<ProductModel> products)
{
    for each (var prd in products) { if prd.IsChecked }
    ... Do something else
}

Model

public class ProductModel
{ 
    String ProductName
    String CategoryName
    Bool IsChecked
}

View

@model List<ProductModel>
<form>
   @for (int i = 0; i <= Model.Count; i++)
    {
           @Html.TextBlockFor(m => Model[i].ProductName)
            @Html.CheckBoxFor(m => Model[i].IsChecked)
     }
     <input type"submit" />
<\form>