Reputation: 3563
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="[email protected]" class="js-favorite-checkbox" type="checkbox" @(Model.Checked ? "checked" : "") data-product-id="@Model.Id">
</div>
Upvotes: 0
Views: 1039
Reputation: 15559
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
Upvotes: 0
Reputation: 1256
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>
Upvotes: 1