Bind dynamic inputs

戏子无情 提交于 2019-12-13 21:27:13

问题


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( /* ??? /*)

回答1:


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)



回答2:


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?



来源:https://stackoverflow.com/questions/53255850/bind-dynamic-inputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!