I have a form that has a dynamic inputs, so I don't know the count and names of the inputs, as you can see in the code below, they came from database.
<div class="panel-body">
<form asp-action="BrandFilter" method="get">
<div class="form-group">
@foreach (var brand in Model)
{
<div class="checkbox">
<label>
<input asp-for="@brand" type="checkbox" />@brand (10)
</label>
</div>
}
</div>
<button class="btn btn-default btn-sm btn-primary"><i class="fa fa-pencil"></i> Apply</button>
</form>
</div>
The question is how to bind all inputs when form is submitted.
public async Task<IActionResult> BrandFilter( /* ??? /*)
I create a demo that you could select the brands and pass all checkboxes' values to controller.
1.Brand.cs
public class Brand
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
}
2.View
@model List<Models.Brand>
<div class="col-md-4">
<form asp-action="BrandFilter" method="post">
<div class="form-group">
@for (int i = 0; i < Model.Count(); i++)
{
<div class="checkbox">
@Html.HiddenFor(m => m[i].Name)
@Html.CheckBoxFor(m => m[i].Selected)
@Html.DisplayFor(m => m[i].Name)
</div>
}
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-default" />
</div>
</form>
</div>
3.controller
public async Task<IActionResult> BrandFilter(List<Brand> brands)
The above answer actually works, but I have found also an another approach.
In CSHTML file:
<input name="@brand.Name" type="checkbox" value="true"/>@brand.Name (@brand.Count)
Method signature:
public async Task<IActionResult> BrandFilter(Dictionary<string, bool> brands)
In this approach you are receiving only the checked inputs which leads to a way less data sent to the server.
So instead of posting another question, comment under this answer and say What do you think for both approaches and which one is better?