【问题标题】:Razor pages, return all checkboxes as a list of values剃刀页面,将所有复选框作为值列表返回
【发布时间】:2021-08-27 06:42:50
【问题描述】:

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

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&lt;string&gt; 类型,当提交表单时,我希望我的列表中填充与选中复选框对应的所有值(url

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

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

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

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

【问题讨论】:

    标签: c# forms asp.net-core checkbox


    【解决方案1】:

    正如错误信息所说,如果你在复选框中使用标签助手,它只允许 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...
        }
    }
    

    【讨论】:

      【解决方案2】:

      所以我认为 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

      【讨论】:

        猜你喜欢
        • 2020-03-02
        • 1970-01-01
        • 2021-08-14
        • 2022-11-28
        • 2019-07-24
        • 1970-01-01
        • 2018-12-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多