绑定到模型的 MVC 复选框列表

MVC checkbox list bounding to model

我正在尝试收集用户为复选框列表选择的所有选项。复选框列表是使用 foreach 循环构建的,我有一个 int[] 试图将 id 放入其中。任何帮助都会很棒。

查看

 @{
 int idxFormats = 0;
 foreach (var item in Model.ListOfFormats)
 {
     <div class='col-md-6'>
          <input type="checkbox" value=@item.Value name="chkFormat" />
          <label asp-for=@item.Selected>@Html.Raw(@item.Name)</label>
          @Html.HiddenFor(m => Model.selectedFormats[idxFormats]);
     </div>
     idxFormats++;
  }
  @Html.ValidationMessageFor(model => model.selectedFormats[idxFormats])
  }

型号

public List<GenericValues> ListOfFormats { get; set; }
[Display(Name = "At least one 'Format' must be selected")]
public int[] selectedFormats { get; set; }

如果您希望将 id 作为您的 idxFormats 的值,那么请在您的复选框中使用此代码:

<input type="checkbox" value=@item.Value name="chkFormat" id="@idxFormats" />

编辑:

我对c#不太熟悉,我用最少的代码测试过:

// Replace the model correct path by yours
@model IEnumerable<WebApplication1.Models.MyModels.ListOfFormats>


@{
    int idxFormats = 0;
    foreach (var item in Model)
    {
        <div class='col-md-6'>
            <input type="checkbox" value=@item.Value name="chkFormat" id="@idxFormats"/>
            <label>@Html.Raw(@item.Name)</label>
            
        </div>
        idxFormats++;
    }
    
}

将复选框名称更改为 selectedFormats

<input type="checkbox" value=@item.Value name="selectedFormats" />

测试示例:

型号:

public class Test
{
    public List<GenericValues> ListOfFormats { get; set; }
    public int[] selectedFormats { get; set; }
}

public class GenericValues
{
    public int Value { get; set; }
    public string Name { get; set; }
    public bool Selected { get; set; }
}

查看:

@model Test

@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Index</h1>

<form method="post">
    @{
        foreach (var item in Model.ListOfFormats)
        {
            <div class='col-md-6'>
                <input type="checkbox" value=@item.Value name="selectedFormats" />
                <label asp-for=@item.Selected>@Html.Raw(@item.Name)</label>
            </div>
        }
    }
    <input type="submit" value="submit" />
</form>

控制器:

public IActionResult Index()
{
    Test test = new Test
    {
        ListOfFormats = new List<GenericValues>
        {
            new GenericValues
            {
                Name = "A",
                Value = 1,
            },
            new GenericValues
            {
                Name = "B",
                Value = 2,
            },
            new GenericValues
            {
                Name = "C",
                Value = 3,
            }
        }
    };
    return View(test);
}

[HttpPost]
public IActionResult Index(Test test)
{

    return Ok();
}

结果: