0

I will be presenting my users a form to fill out a form to get some quotes. There will be a series of objects (~15 or so) that I want to present as check boxes. The issue is, I don't want to hardcode in 15 bools, I want them to be dynamically built on a per-user basis. So a simplified version of the model I came up with would look something like this:

public class InqueryViewModel
{
    public string Origin { get; set; }
    public string Destination { get; set; }
    public decimal Weight { get; set; }
    public IEnumerable<Option> AdvancedOptions { get; set; }
}

public class Option
{
    public bool Selected { get; set; }
    public string Type { get; set; }
}

The problem is, I can't figure out how to bind the AdvancedOptions. I tried this:

@foreach (var option in Model.AdvancedOptions)
{
    <div class="col-xs-4">
        <div class="col-xs-1">
            @Html.CheckBoxFor(x => option.Selected)
        </div>
        <div class="col-xs-2">
            @option.Type
        </div>
        <div class="col-xs-1"></div>
    </div>
}

But that doesn't work. I'm pretty new to trying to use front-end forms with MVC, so I may just be going about this the wrong way. Any suggestions?

Pharylon
  • 9,796
  • 3
  • 35
  • 59

1 Answers1

2

You are trying to model bind to a list. The easiest way to achieve this is to change your view model to use an IList<Option> and then do the following:

@for(var i = 0; i < Model.AdvancedOptions.Count; i++)
{
    @Html.CheckBoxFor(m => Model.AdvancedOptions[i].Selected)
}

See Phil Haacks post about binding to collections for more information

James Hull
  • 3,669
  • 2
  • 27
  • 36
  • Oops, I may have spoken too soon. When the `AdvancedOptions` post back, they've their `Type` property is now null. Seems that checkbox isn't preserving the data. – Pharylon Jul 01 '14 at 14:55
  • You will need a hidden input to post back the type `@Html.HiddenFor(m => Model.AdvancedOptions[i].Type)` – James Hull Jul 01 '14 at 14:59