如何获取剃须刀页面中的所有选择列表项?

How to get all selectlist items in razor page?

我有一个 select 列表:

[BindProperty]
public List<SelectListItem> FooList { get; set; }

然后将列表实例化为空列表并加载剃刀页面。然后,该列表由客户端的用户使用 jquery 填充。在提交表单之前,服务器不知道列表中的项目。到目前为止,还不错。

在页面中,我正在使用 select 标签助手,就像这样...

   <select asp-for="FooList" multiple="multiple" asp-items="FooList" class="form-control form">

我想知道如何使用模型绑定检索多个 select 列表 "list box" 中的所有项目(无论它们是否 selected)?

我正在使用 razor pages 2.2,但我真的很难弄明白。

        public IActionResult OnPost()
    {

        // not sure how to get the selectlist and all of its items?
        foreach (var item in FooList)
        {

            // do stuff with the items

        }

        return Page();
    }

我知道这一定很简单,只需要一双全新的眼睛来指引我正确的方向。谢谢!

I'm wondering how can I retrieve all items in a mulitple selectlist "list box" (whether they're selected or not) OnPost using model binding?

你不能。只有 selected 项目的值被发布并且可以参与模型绑定。如果您想在多个 select 列表中获取 selected 项目,您需要将它们绑定到一个集合。您的 asp-for 属性应引用您将发布的值绑定到的集合的名称。 List<SelectListItem> 类型不应该有 [BindProprty]。它们仅代表填充 select 列表的项目。

您可以了解有关 the basics of Select Lists in Razor Pages here 的更多信息。