0

I have multiple checkboxes binded from ViewBag list. I have used this pattern while Add Record. But now I have situation of Edit . I have saved the selected checkbox IDs in different table. Now in Edit,how I can make them selected as per user selection done while adding that record?

@foreach (var item in ViewBag.Features)
{
    <div class="form-group form-animate-checkbox col-md-4 col-sm-12">
        <input type="checkbox" class="checkbox Amenities" value="@item.ID" name="@item.Name">
        <label class="lblamenities">@item.Name</label>
    </div>
}
Harjeet Singh
  • 388
  • 2
  • 6
  • 22
  • 1
    Yo would need to set the `checked` value of each checkbox. But your code is an awful way to try and bind to a model and will never give true 2-way model binding, or any validation. Use a view model that contains properties `int ID`, `string Name` and `bool IsSelected` so that you can bind to the `Selected` property using `@Html.CheckBoxFor()` –  Mar 17 '17 at 06:54
  • For an example, refer [this answer](http://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416#29554416) –  Mar 17 '17 at 06:55

1 Answers1

0

In ViewBag.Features is list type variable, this contain the id and name, but in your requirement you need to select those check box previous you save. So you can take another parameter or variable selected as bool type, those id are saved in our database the selected variable is true otherwise false.

In view page make check for checked or not, Plz see the below code....

@foreach (var item in ViewBag.Features)
{
    <div class="form-group form-animate-checkbox col-md-4 col-sm-12">
        <input type="checkbox" class="checkbox Amenities" value="@item.ID" name="@item.Name" checked='@(item.selected?"checked":"")'>
        <label class="lblamenities">@item.Name</label>
    </div>
}
Rajkishor
  • 1
  • 1
  • This is wrong - if the value of `item.selected` is `trie` it renders `checked="checked"` and if its `false` it renders `checked`, both of which result in the checkbox being checked –  Mar 17 '17 at 07:15
  • It would need to be `` –  Mar 17 '17 at 07:18
  • you not see the code carefully. Because i am using ternary operator in true it render checked="checked" and false it renders checked="" – Rajkishor Mar 17 '17 at 07:18
  • 2
    Exactly. Setting the `checked` attribute means its checked (try your code first!) –  Mar 17 '17 at 07:19
  • Try your code! It does not work - `checked="checked"` or `checked=""` or `checked="false"` or `checked="anything"` are all the same - they set the checked attribute and the checkbox is checked! –  Mar 17 '17 at 07:21
  • You are right it should like @(item.selected?"checked":null) – Rajkishor Mar 17 '17 at 07:24