I have a CreateViewModel
.
public class CreateViewModel
{
public AttributesViewModel AttributesInfo { get; set; }
}
The AttributesViewModel
is sent to a partial view.
public class AttributesViewModel
{
public AttributesViewModel()
{
ChosenAttributes = new List<int>();
}
public List<Attributes> Attributes { get; set; }
public List<int> ChosenAttributes { get; set; }
}
The List of Attributes is outputted in the partial view. Each one has a checkbox.
foreach (var attribute in Model.Attributes)
{
<input type="checkbox" name="ChosenAttributes" value="@attribute.ID" /> @Attribute.Name
}
When I post CreateViewModel
, AttributesInfo.ChosenAttributes
is always empty even though I checked some boxes. How do I properly name each checkbox so that it binds to the ChosenAttributes List?
My Solution
I took Stephen Muecke's suggestion to do the two way binding. So, I created a CheckboxInfo class that contained Value, Text, and IsChecked. I created a EditorTemplate for it:
@model Project.CheckboxInfo
@Html.HiddenFor(model => model.Text)
@Html.HiddenFor(model => model.Value)
@Html.CheckBoxFor(model => model.IsChecked) @Model.Text
One GIANT caveat. To get this to work properly, I had to create an EditorTemplate for the AttributesViewModel class. Without it, when CreateViewModel is posted, it cannot link the checkboxes to AttributesInfo.
Your naming the checkbox
name="ChosenAttributes"
butCreateViewModel
does not contain a property namedChosenAttributes
(only one namedAttributesInfo
). You may be able make this work usingbut the correct approach is to use a proper view model that would contain a boolean property (say)
bool IsSelected
and use strongly typed helpers to bind to your properties in afor
loop or using a customEditorTemplate
so that your controls are correctly names and you get 2-way model binding.