Search code examples
c#razor-pages

ASP.net razor page checkbox not bound


Trying to bind the checkboxes when I do a post. However, I'm probably overlooking something, as my list is always empty.

Here my code:

        @foreach (var item in Model.CubeList)
        {
            <label name="" id="[email protected]" class="control-label">
                <input type="checkbox" class="radio-inline" name="CubeList" id="@item.CubeName" />
                @item.CubeName
            </label>
        }

With this list I want to bind to:

    [BindProperty] public IList<CubeTableInDatabase> CubeList { get; set; }

In the class CubeTableInDatabase I currently only have one item:

  public class CubeTableInDatabase
  {
    [Key]
    public string? CubeName { get; set; }
  }

What I try is to have checkboxes for each item in the list of CubeList. And then on the post I want to check which one is checked and which one is not. However, on my post action the CubeList is always empty (no matter what I select). What am I doing wrong?


Solution

  • Check out the explanations here:
    https://www.learnrazorpages.com/razor-pages/forms/checkboxes#collections-of-complex-objects

    You'll probably want to add another boolean property in your class, IsSelected:

    public class CubeTableInDatabase
    {
      [Key]
      public string? CubeName { get; set; }
        
      public bool IsSelected { get; set; }
    }
    

    And then have something like:

    <input asp-for="item.IsSelected" /> @item.CubeName