0
votes

i have a class

public class CustomBenefitCommittee
    {
        public int PlanOptionId { get; set; }
        public bool IsChecked { get; set; }
        public string PlanOptionName { get; set; }
    }

and i have took this class as a list type of model in my razer view

@model List<MIHR.Business.CustomClasses.CustomBenefitCommittee>
@{
    int Counter = 0;
}

<table class="table table-bordered" id="tblPlanLst">
        <thead>
            <tr>
                <th>
                     select
                </th>
                <th>
                    Benefit Option
                </th>

            </tr>
        </thead>

        <tbody>

            @foreach (var Enrol in Model)
            {
                <tr>
                    <td> <input type="checkbox" name="customBenefitCommittee[@Counter].IsChecked"  class="clsCheck" /></td>
                    <td>
                        @Enrol.PlanOptionName
                    </td>

                </tr>
                        Counter++;
            }

        </tbody>
    </table>
<input type="submit" id="btnSubmitSave" value="Save" name="buttonType" class="btn btn  btn-primary">

now when i post this form to controller with checking the checkbox i get always false in this checkbox IsChecked property. can anyone help me out with it.

2
Once again I have update my answer please check it's worked for you or not - RAJNIK PATEL
Your checkbox does not have a value. Generate your html correctly using @for(int i = 0; i < Model.Count; i++) { @Html.CheckBoxFor(m => m[i].IsChecked) } - refer also Post an HTML Table to ADO.NET DataTable - user3559349

2 Answers

1
votes

You can also use this way :

@{
    var IsChecked = "";
    if (Enrol.IsChecked == true)
    {
        IsChecked = "checked='checked'";
    }
}
<input type="checkbox" name="customBenefitCommittee[@Counter].IsChecked" @IsChecked value="true" />

In this you get true if checkbox is checked and null while checkbox is unchecked

public class CustomBenefitCommittee
    {
        public int PlanOptionId { get; set; }
        public bool? IsChecked { get; set; }
        public string PlanOptionName { get; set; }
    }

OR You can also use this way :

@Html.CheckBox("customBenefitCommittee[" + Counter + "].IsChecked", Enrol.IsChecked ?? false, new { @class = "clsCheck" })

OR You can also use this way :

@Html.CheckBoxFor(model => model[@Counter].IsChecked)
1
votes

My problem was solved by RAJNIK PATEL's answer.

I have a view model that contains other view models on a tabbed page. Each tab is a different view model. When submitted, all the tabs are saved.

To get a dynamically generated set of checkboxes, I had to make the names indicate the correct view model within the viewmodel I was using.

public class AViewModel{
    public AnotherViewModel {get;set;}
}

So my checkboxes generated by a loop for types look like this. checkboxid is my generated name.

 @Html.CheckBox("ModifyRolePermViewModel." + checkboxid)