TestzWCh TestzWCh - 1 year ago 169
C# Question

@Html.HiddenFor does not pass value from CheckBoxFor to controller

Im trying to pass from @Html.CheckBoxFor to controller but it does not pass true values. i have ViewModel containing an IList of another ViewModel which contains bool isSelected which doesnt seem to be passed. The code looks like that

public class PackageItemsViewModel

public IList<ItemsViewModel> items{ get; set; }

public class ItemsViewModel
public int Id { get; set; }

public string Type { get; set; }

public bool isSelected { get; set; }

and in View

@for (var i = 0; i < Model.items.Count; i++)
@Html.HiddenFor(x => x.devices[i].Id)

@Html.HiddenFor(x => x.items[i].isSelected)
@Html.CheckBoxFor(x => x.items[i].isSelected)

Answer Source

The DefaultModelBinder binds only the first value it finds with a matching property. In you case your @Html.HiddenFor(x => x.items[i].isSelected) is rendering the initial value you sent to the view, and because its before the checkbox, you will only ever bind to that initial value (your checkbox is being ignored).

Simply remove the @Html.HiddenFor(x => x.items[i].isSelected) and the value will be correctly bound.

Note that the CheckBoxFor() method generate both a checkbox (with value="true" and a hidden input with value="false" so that if the checkbox is checked, both true and false are posted (but only true is bound) and if unchecked. only false is posted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download