I am working on an MVC application where the Model class Item has a List named AvailableColours as a property.
<
Make sure to add the constructor in the the class and declare list inside it. Other wise it would declared take null value which you won't be able to set for later.
public class Item
{
public Item(){
AvailableColours =new List<Color>();
}
}
Models
public class Item
{
public List<Colour> AvailableColours { get;set; }
}
public class Colour
{
public int ID { get; set; }
public string Description { get; set; }
public bool Checked { get; set; }
}
Note the Checked property
View for loop
@using (Html.BeginForm("Create", "Item", FormMethod.Post))
{
<div>
@Html.LabelFor(model => model.AvailableColours)
@for(var i = 0; i < Model.AvailableColours.Count; i++)
{
@Html.HiddenFor(m => Model.AvailableColours[i].ID)
@Html.HiddenFor(m => Model.AvailableColours[i].Description)
@Html.CheckBoxFor(m => Model.AvailableColours[i].Checked)
@Model.AvailableColours[i].Description<br/>
}
</div>
<input type="submit" value="Submit" />
}
Note the for loop insted of foreach to enable model binding and the hidden fields to allow the values to be posted back to the controller
Model Binding To A List
Controller post
[HttpPost]
public ActionResult Create(Item model)
{
//All the selected are available in AvailableColours
return View(model);
}
Thank you for all of the advice - invaluable but there was one more change I needed to make before my program would bind to the model and that was to add a getter and a setter to the List as in:
public class CartViewModel
{
public List<CartRowViewModel> cartRows {get; set; }
public CartViewModel()
{
this.cartRows = new List<CartRowViewModel>();
}
}