I have a form that needs to capture values from checkboxes in a form. Each checkbox should have an integer value and when the form is submitted, the view model should validate the values and at least one should be selected.
I need to also build a two way binding so that the framework will auto select the options that are selected when the page is loaded.
Here is what my model looks like
public class SomeViewModel
{
[Required(ErrorMessage = "You must select at least one site.")]
[Display(Name = "All site to have access too")]
public int[] Sites { get; set; }
}
The I encapsulate my ViewModel in a Presentation class called Presenter
like so
public class Presenter
{
public SomeViewModel Access { get; set; }
public IEnumerable<Site> AvailableSites { get; set; }
}
Now, I pass Presenter
to my view and want to render the
And here is how my view looks like
<div class="form-group">
@Html.LabelFor(m => m.Access.Sites, new { @class = "col-sm-2 control-label" })
<div class="col-sm-10">
@for (int i = 0; i < Model.AvailableSites.Count(); i++ )
{
<label class="radio-inline">
@Html.CheckBoxFor(m => m.Access.Sites[i])
</label>
}
</div>
@Html.ValidationMessageFor(m => m.Access.Sites)
</div>
since @Html.CheckBoxFor
accepts bool value, and I am passing an integer I am getting an error on the @Html.CheckBoxFor(m => m.Access.Sites[i])
line inside the view.
How can I correct this issue? and how can I correctly render checkboxes in this view?