-1

So i'm facing this problem that I don't remember how to solve it, but i'm sure it needs some handcraft to achieve it by using razor (without jquery)

Basically you have

Model

public class MyModel {
    --Post will write here:
    public List<Guid> SelectedIds {get; set;}

    --This is the actual list of values, ids, etc...
    public List<Option> Options {get;}
}

Controller

[HttpPost]
    public ActionResult Save (MyModel model)

Class Option

public class Option {
    public String Name {get; set;}
    public Guid Id {get; set;}
}

Question:

I would like to have a list of checkboxes binded to "Options" property, but when I submit the form, I would like to retrieve IDS only of the selected values, would be great if I could put them inside "SelectedIds" property.

Any clue how to solve this?

Thanks in advance.

Yogurtu
  • 2,656
  • 3
  • 23
  • 23
  • 2
    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) –  Apr 07 '18 at 21:24
  • hmm, so that approach might not have my expected result, but is actually acceptable. Thanks – Yogurtu Apr 08 '18 at 23:02

1 Answers1

0

So, handcrafted way might be like this:

for(int i = 0; i < Model.Options.Count; i++)
  {
    @Html.HiddenFor(m => m.Options[i].ID)
    @Html.CheckBoxFor(m => m.Options[i].IsSelected)
    @Html.LabelFor(m => m.Options[i].IsSelected, Model.Options[i].Name)
  }

But in addition, I needed to create a new class for my "Option", to include the IsSelected flag. (Usually I don't have this field as a value in my database, it will result in the representation of an MxN record)

Also, Class Option is auto-generated, so bad idea to change it, instead inheritance will be enought.

public class OptionSelectable : Option {
    public Boolean IsSelected {get; set;}
}

And that's it, thanks @Stephen Muecke for the tip

Yogurtu
  • 2,656
  • 3
  • 23
  • 23