简体   繁体   English

Razor 页面,将所有复选框作为值列表返回

[英]Razor pages, return all checkboxes as a list of values

I want my checkboxes in a form to return as a list of all the values for selected checkboxes我希望表单中的复选框作为所选复选框的所有值的列表返回

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>
    }

Where Input.ChosenPhotos is type List<string> and when the form is submitted I want my list to be populated with all of the values ( url ) that correspond with a checked checkbox其中Input.ChosenPhotosList<string>类型,提交表单时,我希望我的列表中填充与选中的复选框对应的所有值( url

When I run I get an error that basically says checkboxes can only return a bool or string.当我运行时,我收到一个错误,基本上说复选框只能返回一个布尔值或字符串。 Not a list of strings or bools.不是字符串或布尔值的列表。

Problem is my list is of inderterminet length so I cant have an input model that has an individual property for each checkbox.问题是我的列表是不确定的长度,所以我不能有一个输入 model ,每个复选框都有一个单独的属性。

I'm not sure what the optimal solution is here?我不确定这里的最佳解决方案是什么?

Im using Razor Pages btw我正在使用 Razor 页面顺便说一句

As the error message said, if you use tag helper in checkbox, it only allows bool or string type property.正如错误消息所说,如果您在复选框中使用标签助手,它只允许 bool 或 string 类型的属性。 For your scenario, you could change asp-for to name like below:对于您的方案,您可以将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>
}

Backend code:后端代码:

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

So I think Rena's answer would work, but this is the solution I found and have just implemented (before Rena's answer was posted)所以我认为 Rena 的答案会起作用,但这是我找到并刚刚实施的解决方案(在 Rena 的答案发布之前)

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

https://github.com/Melvinmz/chkBoxSnippet https://github.com/Melvinmz/chkBoxSnippet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM