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

后端 未结 2 1589
生来不讨喜
生来不讨喜 2020-12-09 21:12

Sorry but most of my searches take me to old MVC codes. Any help will be appreciated.

In MVC 6 with tag helpers, how do you code a set of checkboxes:

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 21:46

    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 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++)
        {
            
    @*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)
    } }

    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.

提交回复
热议问题