0

I have a checkbox and when I press it, I need to add checked attribute to cshtml.

When I deselect the checkbox, I need to remove this attribute. How can I do it?

Now, when I press it, nothing is happens. I need to change the value of Checked variable somehow.

View model:

public class ListProductVM
{
    public int Id { get; set; }
    public bool Checked { get; set; }
}

.cshtml page:

    <div class="compare-checkbox form-checkbox">
        <input name="compare-@Model.Id" class="js-favorite-checkbox" type="checkbox" @(Model.Checked ? "checked" : "") data-product-id="@Model.Id">
    </div>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Amazing User
  • 3,473
  • 10
  • 36
  • 75

2 Answers2

1

You should use jquery/javascript for this. Add this to your page

 <script>

    $('.js-favorite-checkbox').change(function() {
        if(this.checked) {
            this.setAttribute('checked', 'checked');
        }
        else
        {
            this.removeAttribute("checked"); 
        }
    });

 </script>
sicKo
  • 1,241
  • 1
  • 12
  • 35
0

You can try CheckBoxFor HTML helper:

@model ListProductVM

<div class="compare-checkbox form-checkbox">
    @Html.CheckBoxFor(m => m.Checked, new { @class="js-favorite-checkbox", @data_product_id="@Model.Id" })
    @Html.LabelFor(m => m.Checked)
</div>

Note that data_product_id will be rendered as data-product-id in the html file: more info here


Here is a demo

Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137