1

In my view I have a checkbox and I need to add an attribute to it when I select product on the page. I can't understand, how to dynamically add or remove this attribute? Now I wrote it in cshtml and all itens on page are checked, but I need to show this attribute only when user press on the checkbox.

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

_ListProduct.cshtml

@model Bs.WebApp.ViewModels.Product.Shared.ListProductVM

<div class="compare-checkbox form-checkbox">                     // This
    <input name="compare-@Model.Id" class="js-favorite-checkbox" checked type="checkbox" data-product-id="@Model.Id">
</div>
Amazing User
  • 3,473
  • 10
  • 36
  • 75

1 Answers1

1

You can use this way to check if your model is checked or not:

<input @(Model.Checked ? "checked" : "") name="compare-@Model.Id" class="js-favorite-checkbox" type="checkbox" data-product-id="@Model.Id">
Tân
  • 1
  • 15
  • 56
  • 102
  • Thanks. But how can I see this attribute in browser? Should it appear in Elements window when I press checkbox? Because it don't appear – Amazing User Apr 15 '20 at 15:51
  • 1
    @DimaKozyr `@(Model.Checked ? "checked" : "")` is a conditional operator. When your model is checked, it will add `checked` attribute to the input element. Otherwise, it's empty. – Tân Apr 15 '20 at 16:05
  • 1
    @DimaKozyr You can try to set `Model.Checked = true` and check the result. – Tân Apr 15 '20 at 16:07
  • Yes, I can set `Model.Checked = true` and I can see the attribute. But if I don't do it and I just launch the project, there is no attribute and it is correct. But after that, without stop debugging, when I press checkbox in browser, I expect that it will appear like on my screenshot. But I don't see it – Amazing User Apr 15 '20 at 16:17
  • 1
    @DimaKozyr Ahh, you cannot see the attribute while clicking on the checkbox by default. That's based on your browser. But you can still check it's checked or not. – Tân Apr 15 '20 at 16:43