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



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

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

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

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

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

我正在使用Razor Pages btw

正如错误消息所说,如果在复选框中使用标记helper,它只允许bool或字符串类型属性。对于您的场景,您可以将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

最新更新