Kayani
Kayani

Reputation: 972

Mvc Checkboxes Bind with model Bool

I have a mvc model with bool isSelected property. I pass a IEnumerable to my view and return it back to my controller. The issue is that I always get false for checkboxes even if they are checked Here is some code:

Model :

public class User
{
    public string Name { get; set; }
    public int ID { get; set; }
    public string Email { get; set; }
    public bool selected { get; set; }
    public string company { get; set; }
    public string role { get; set; }
}

View:

for(i=0;i<Model.Count();i++) 
{
   @Html.CheckBoxFor(modelItem => modelItem.ElementAt(i).selected)
}

Upvotes: 0

Views: 738

Answers (1)

user3559349
user3559349

Reputation:

What you are doing with this loop is creating multiple elements with the same name (in your case <input type="checkbox" name="selected" ...>. Since this is a collection, your name attributes should be ..name="[0].selected.., ..name="[1].selected..

If possible change the collection to IList so that you can index the names

for (int i = 0; i < Model.Count; i++)
{
  @Html.CheckboxFor(m => m[i].selected)

Alternatively you can use a custom EditorTemplate for typeof User and use

@Html.EditorFor(m => m)

Upvotes: 4

Related Questions