In MVC 6, how to code checkbox list in view and pass the checked values to the controller?

萝らか妹 提交于 2019-11-28 09:18:38

This is finally what I did to make it to work. I am not sure if this is the best way to do it. I had to still use the html helpers because the tag helpers do not work.

Model:

public List<PhoneOption> PhoneOptions { get; set; }
. . .
PhoneOptions = repository.GetPhoneOptions().ToList();

View:

@if (@Model.PhoneOptions != null && @Model.PhoneOptions.Count() > 0)
{
    for (int i = 0; i < @Model.PhoneOptions.Count(); i++)
    {
        <div>
            <input asp-for="@Model.PhoneOptions[i].IsOptionSelected" type="checkbox" />
            <label asp-for="@Model.PhoneOptions[i].IsOptionSelected">@Model.PhoneOptions[i].OptionName</label>

            @*If these are not included, all OptionIds become 0 and all OptionName becomes null*@
            @Html.HiddenFor(x => @Model.PhoneOptions[i].OptionId)
            @Html.HiddenFor(y => @Model.PhoneOptions[i].OptionName)
        </div>
    }    
}

I hope this helps someone else who is having the same checkbox list issues.

UPDATE: I've updated the html helpers to tag helpers above.

This is how the syntax should be in your for each asp-for should be wrapped in a string with quotation marks

 @foreach (var option in Model.PhoneOptions)
        {
            <div>
                @{ string cbId = "PhoneOption_" + @option.OptionId; }
                <input asp-for="@option.IsOptionSelected" type="checkbox" value="@option.IsOptionSelected" id="@cbId" name="@cbId" />
                @Html.Label(@cbId.ToString(), @option.OptionName)
                @*This is causing invalid operation exception*@
                @*<label asp-for="@cbId">@option.OptionName</label>*@ 
                <span asp-validation-for="@cbId" class="text-danger" role="alert"></span>
            </div>
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!