mercredi 4 novembre 2015

Passing a List of Checkbox to Controller

I generate a list of available objects and the UI has checkboxes to select the objects. The UI is not exactly generated based on my Model class because I was unable to do so.

Controller Create

public ActionResult Create(int id)
{
    var model = new List<Config_OptionVal>();
    foreach (var item in model)
    {
         item.ConfigurationCollectionID = id;
         item.ConfigurationCollection = db.ConfigurationCollection.FirstOrDefault(x => x.ConfigurationCollectionID == id);
    }
    var lsysid = db.ConfigurationCollection.FirstOrDefault(x => x.ConfigurationCollectionID == id).LsystemID;
    return View(model);
}

Create Post Method

public ActionResult Create(List<Config_OptionVal> Config_OptionVal)
{
    if (ModelState.IsValid)
    {
        foreach(var item in Config_OptionVal)
        {
            foreach(var check in item.OptionValChecked)
            {
               //This is the part where i do not know what should be written
            }
        }
    }
}

Model Class

public class Config_OptionVal
{
    public int Config_OptionValID { get; set; }
    public int OptionValueID { get; set; }
    public int ConfigurationCollectionID { get; set; }
    public bool OptionValChecked { get; set; } //This doesn't really have any significance. I am only interested in the values of ConfigurationID and OptionValueID

    public virtual OptionValue OptionValue { get; set; }
    public virtual ConfigurationCollection ConfigurationCollection { get; set; }
}

View

@model List<TEDALS_Ver01.Models.Config_OptionVal>
<table class="table">
<tr>
      <th>Option</th>
       <th>Option Values</th>
</tr>
@int i=0;
@foreach(var item in Model)
{
  foreach (var op in item.ConfigurationCollection.Lsystem.Options)
  {
      <tr>
         <td>@op.OptionName</td>
         <td>             
            @foreach (var ov in op.OptionValues)
            {
              Html.CheckBoxFor(model=>model[i].OptionValue);
              i++;
             }
           </td>
        </tr>
     }
   }        
 </table>

I understand that Checkbox can only be applied to a Boolean value (Correct me if I am wrong). And that's the reason why I added the property OptionValueChecked. Then I get the i do not exist in the current context. I also tried FormCollection, but none of the properties in the View were accessible(But it could be that I did not use the Form Collection properly coz I have never tried with that before).

Any idea how I could save to the table the value of ConfigurationCollectionID and OptionValueID to the database.




Aucun commentaire:

Enregistrer un commentaire