-1

There are razor checkbox controls in application which needs to be repeated for each of the collection. But for the collection number second onwards below code passes nothing as value for checkbox:

<div class="checkbox">
    <label class="checkbox-inline">
        @Html.CheckBoxFor(m => m.Collection[i].Item)Some Label
    </label>
</div>

The viewmodel is:

public class Items{ 
   public List<Collection> Collection{get; set;}
}
public class Collection{
    public bool Item { get; set; }
}
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
Tisal
  • 155
  • 1
  • 4
  • 12
  • tried `@Html.CheckBoxFor(m => m.Collection[i].Item,new{@checked="checked"})` but that also didnot helped – Tisal Feb 18 '16 at 15:03
  • 3
    Show use your relevant view model and razor code. – Shyju Feb 18 '16 at 15:03
  • What is not working. Assuming the code you have shown is in a `for` loop - `for(int i = 0; i < Model.Collection.Count; i++) { ... }` then it will work. –  Feb 18 '16 at 20:56

2 Answers2

1

Assuming your HttpPost action's parameter is an object of

[HttpPost]
public ActionResult Create(Items model)
{
   //to do : Save and Redirect
}

You need to make sure that the checkboxes in your form will have the name matching to your ViewModel property hierarchy. So , for model binding to work, you need to have your checkboxes with names like this

<input  name="Collection[1].Item" type="checkbox" >

So in your view, Make sure you manipulate the name like that

@model Items
@using (Html.BeginForm())
{

    for (int index = 0; index < Model.Collection.Count; index++)
    {
        var collection = Model.Collection[index];
        @Html.CheckBox("Collection["+index+"].Item",collection.Item)
    }
    <input type="submit"/>

}

Another (better) option is to use Editor Templates. With this approach, you do not need to manipulate the form field name. Here is a complete post which explains the step by step

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
0

Instead of Item write selected

<div class="checkbox">
   <label class="checkbox-inline">
     @Html.CheckBoxFor(m => m.Collection[i].selected)Some Label
    </label>
</div>

Or try this

 @Html.CheckBoxFor(m => m[i].Checked,new {Style ="vertical-align})
Keennary
  • 1
  • 2