0

I have a list of checkboxes and I need to tell which are checked using C#. How would I tell which individual checkboxes are checked and then add their values together? I am using Asp.Net Core, if that could be helpful

<div class="row">
    <form method="post" class="offset-3 col-5 border">
        <div id="Colors" class="form-group" type="checkbox">
            <label class="form-check-label">Colors</label>
            <div class="form-check">
                <input id="Red" class="form-check-input" type="checkbox" value="1">
                <label class="form-check-label">Red</label>
            </div>
            <div class="form-check">
                <input id="Yellow" class="form-check-input" type="checkbox" value="2">
                <label class="form-check-label">Yellow</label>
            </div>
            <div class="form-check">
                <input id="Green" class="form-check-input" type="checkbox" value="4">
                <label class="form-check-label">Green</label>
            </div>
            <div class="form-check">
                <input id="Blue" class="form-check-input" type="checkbox" value="8">
                <label class="form-check-label">Blue</label>
            </div>
            <div class="form-group">
                <input type="submit" value="Post" class="btn btn-primary" />               
            </div>
        </div>
    </form>
</div>
Ahmad Shahbaz
  • 222
  • 2
  • 5
  • 20
Bubinga
  • 613
  • 12
  • 29

1 Answers1

1

If you are using Jquery and you want to get all checkboxses are checked then you can do what you need like below :

    var selected = [];
$('.form-check-input input:checked').each(function() {
    selected.push($(this).attr('name'));
});

if you are using another Javascript librarry, you should do same.

if you want to get them in your Controller, so you should follow these steps:

1- Add a name to your Checkbox like (here chose color) :

<input id="Red" class="form-check-input" name="color" type="checkbox" value="1">

2- Add a property to your Model

public class AddPostModel
{
    public List<int> Color { get; set; }
}

In this way, when you post your view, you have all values from checkboxes are checked.

osman Rahimi
  • 1,427
  • 1
  • 11
  • 26