Razor 页面,return 所有复选框作为值列表

Razor pages, return all checkboxes as a list of values

我希望表单中的复选框 return 作为所选复选框的所有值的列表

foreach (string url in ListOfPhotoURLs)
    {
        <div class="form-check form-check-inline">
            <input asp-for="Input.ChosenPhotos" class="form-check-input" type="checkbox" id="PhotosChosen" value="@url">
            <img src="@url" alt="photo from url @url" width="250">
            <span class="text-danger" asp-validation-for="Input.ChosenPhotos"></span>
        </div>
    }

其中 Input.ChosenPhotosList<string> 类型,当提交表单时,我希望我的列表中包含与选中的复选框对应的所有值 (url)

当我 运行 我得到一个错误,基本上说复选框只能 return 布尔值或字符串。不是字符串或布尔列表。

问题是我的列表长度过长,所以我不能有一个输入模型,每个复选框都有一个单独的 属性。

我不确定这里的最佳解决方案是什么?

顺便说一句,我正在使用 Razor Pages

正如错误信息所说,如果你在复选框中使用标签助手,它只允许 bool 或 string 类型属性。对于您的情况,您可以将 asp-for 更改为 name,如下所示:

@foreach (string url in ListOfPhotoURLs)
{
    <div class="form-check form-check-inline">
        <input name="Input.ChosenPhotos" class="form-check-input" type="checkbox" id="PhotosChosen" value="@url">
        <img src="@url" alt="photo from url @url" width="250">
        <span class="text-danger" asp-validation-for="Input.ChosenPhotos"></span>
    </div>
}

后端代码:

public class IndexModel : PageModel
{
    [BindProperty]
    public InputModel Input { get; set; }
    public class InputModel
    {
        public string[] ChosenPhotos { get; set; }
    }
    public void OnPost()
    {
        //do your stuff...
    }
}

所以我认为 Rena 的答案可行,但这是我找到并刚刚实施的解决方案(在发布 Rena 的答案之前)

https://mycodingtips.com/2021/3/23/code-snippet-to-create-a-checkboxlist-in-asp-net-core-razor-page-application

https://github.com/Melvinmz/chkBoxSnippet