'Use of IEnumerable<T> and foreach with hidden fields and checkbox not working to pass parameters from view to controller

What I want to achieve is to present a set of checkboxes to a user with the <span> ProductName and a boolean value if the ProductName is in stock or not. I'd also like these checkboxes to be updatable in the same view. If there has been an update I want to update a table in SQL using the primary key ProductKey.

I have a class Products containing this information:

public class Products
{
    [Key]
    public string ProductKey {get;set;}
    public string ProductName {get;set;}
    public Boolean IsAvailable {get;set;}
}

In practice this issue is a bit complicated as different products can have different attributes. To combat this I've found a solution which creates a IEnumerable model. This is generated prior to the view of interest for this question.

My issue is that I want to be able to loop through my IEnumerable model, see whether the product name is in stock or not (indicated whether the checkbox is checked or not) and be able to update the availability from the same view.

@model IEnumerable<Products>
<form asp-controller="Product" asp-action="FindIfProductInStock">
<div class="row">
    @foreach (var item in Model)
    {
           <div class="form-group">
                <label class="label-checkbox">
                    <input [email protected] type="checkbox" [email protected] />
                    <span>
                        @Html.DisplayFor(modelItem => item.ProductName)
                    </span>
                </label>
            </div>
            <div class="form-group">
                <input [email protected] type="hidden" [email protected] />
            </div>
     }
  </div>
  <div class="form-group">
     <input type="submit" value="Update" class="btn btn-primary" />
  </div>
</form>

Where my FindIfProductInStock controller looks like this:

    [HttpPost]
    public IEnumerable<Products> FindIfProductInStock(IEnumerable<Products> productList)
    {
        return productList;
    }

(I use this controller as of right now to be able to make a break point to see what the actual values of productList is).

The view presented to the user works as intended. The checkboxes are checked if the product is in stock. My issue is that productList contains no data. It has 0 rows and IsAvailable is false and the rest of the values of Products are null. Does anyone know why?

I am using the type="hidden" for ProductKey as I don't want the user to see the field, but I need it to connect the value of IsAvailable to the correct product in my SQL table later on.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source