0

I'm facing a problem. I need to display a set of checkboxes with values coming from a Viewbag in my controller. Below is what I already have:

In the controller :

 ViewBag.disciplines = new SelectList(db.Disciplines, "IdDiscipline", "IntituleDiscipline");

And in my view :

<div class="form-group" id="checkboxes">
    <label class="control-label col-md-2" for="discipline"> Discipline :  </label>
    <div class="col-md-10">
        @foreach (var item in ViewBag.disciplines)
        {
            <input type="checkbox"
                 value="@ViewBag.disciplines.IntituleDiscipline"
                 name="@ViewBag.disciplines.IntituleDiscipline"
                 id="@ViewBag.disciplines.IdDiscipline">
        }
    </div>
</div>

I wish to be able to display checkboxes with values as "IntituleDiscipline" and with ids as "IdDiscipline" (these id's come from the database).

When I execute this, I get an exception as such :

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.Web.Mvc.SelectList' does not contain a definition for 'IntituleDiscipline''.

What can I do to achieve the result please?

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
Nice Kloe
  • 59
  • 1
  • 10
  • Look up the definition of a SelectList in Microsoft's docs and see what properties it exposes. The one you're requesting isn't one of them. I suspect you want to get a value from inside one of the items in your selectlist. Each item will be a SelectListItem. So now you go and look up what properties _that_ object exposes, and choose the one you want. And in your checkbox you might want to start referencing the specific `item` provided to you by the loop, instead of the whole list. – ADyson Aug 09 '18 at 13:02
  • 1
    `SelectList` make no sense for list of checkboxes. And do not use `ViewBag` - use a view model. And for an example of how to implement a list of checkboxes in mvc, refer [Pass List of Checkboxes into View and Pull out IEnumerable](https://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416#29554416) –  Aug 09 '18 at 22:41

1 Answers1

0

The problem is that you're trying to access the whole collection within the foreach, instead of the iterated element, replace @ViewBag.disciplines... with @item...

        @foreach (var item in ViewBag.disciplines)
        {
           <input type="checkbox" value="@item.IntituleDiscipline" name="@item.IntituleDiscipline" id="@item.IdDiscipline">
        }
Kellei
  • 61
  • 4
  • 1
    `item` will not have a property called IntituleDiscipline or IdDiscipline. It's a `SelectListItem`. The list of properties it exposes is documented in Microsoft docs. – ADyson Aug 09 '18 at 13:47
  • thanks for your response @Kellei but the error displayed is the same : Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.Web.Mvc.SelectList' does not contain a definition for 'IntituleDiscipline''. – Nice Kloe Aug 10 '18 at 09:27