How do I implement a checkbox list in ASP.NET Core?

后端 未结 4 787
傲寒
傲寒 2021-01-30 13:20

I am looking to implement a checkboxlist in ASP.NET Core, but am facing some difficulties.

My ViewModel:

public class GroupIndexViewModel
{
    public          


        
4条回答
  •  不知归路
    2021-01-30 13:49

    The question might be already answered but I wanted to explain your issue, so others can understand what's happening.

    You are not aware that you are already specifying the false value to your input, since you're implementing a bad use of attributes.

    Let's take a look at your view

    @model GroupIndexViewModel
    
      @for (var i = 0; i < Model.Filters.Length; i++) {
    • }

    So, first. You are creating input elements from an array of Filter. Now let's take a closer look at your input element.

    
    

    Now, let me explain this.

    1. You are specifying a type, using the type attribute.
    2. You are specifying an id, using the id attribute.
    3. You bind the input to the model, using the asp-for tag helper.
    4. You specify a value for the input, using the value attribute.
    5. Finally, you set the input as checked, with the checked attribute.

    If you take a look at the Tag Helpers Documentation, you'll find the relationship between the .Net Type and the Input Type, understanding that:

    Checkboxes holds a boolean value, corresponding to the model, and formatted by the tag helper as type="checkbox".

    Since you're using the type="checkbox" attribute, the Tag Helper value can only be true or false. So, if we go back and look at the input element, you're already specifying a value to the input. Even though the tag-helper can assign a value to the input, it can't override the one already specified. Therefore, your input, will always have the value you've specified, in this case, a boolean is always false by default.

    Now you might think that your input element, has a false value, and for instance, adding the checked="checked" will not change the value to true, since the value attributes, overrides the checked attribute. Causing a bad implementation of both attributes.

    Therefore, you must use only one of the attributes. (Either the value or the checked). You can use them, for convenience. But in this case, you must use the default checked attribute. Since you're implementing a Tag Helper, and the input value, have to be of type boolean. And the checked attribute value, returns a boolean and for instance, is the one used by the Tag Helper.

    So the implementation provided by @dotnetstep should work, since it only declares the tag helper in the input element. So the Tag Helper, handles itself the corresponding attributes of the input.

    @model GroupIndexViewModel
    
      @for (var i = 0; i < Model.Filters.Count; i++) {
    • }

提交回复
热议问题