我有一个选择列表:
[BindProperty]
public List<SelectListItem> FooList { get; set; }
然后,该列表被实例化为空列表,并加载 razor 页面。然后,用户在客户端使用 jquery 填充该列表。在表单发布之前,服务器不知道列表中的项目。到目前为止,一切都很好。在页面中我正在使用选择标签助手,就像这样......
<select asp-for="FooList" multiple="multiple" asp-items="FooList" class="form-control form">
我想知道如何使用模型绑定检索多个选择列表“列表框”中的所有项目(无论它们是否被选中)?
我正在使用 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();
}
我知道这一定很简单,只需要一双新的眼睛来指引我正确的方向。谢谢!
我想知道如何检索多个选择列表中的所有项目 “列表框”(无论是否选择)OnPost 使用模型 绑定?你不能。仅发布所选项目的值并可以参与模型绑定。如果要获取多选列表中的选定项,则需要将它们绑定到集合。您的
asp-for
属性应引用您将发布的值绑定到的集合的名称。
[BindProprty]
类型上不应有
List<SelectListItem>
。它们仅代表填充选择列表的项目。您可以在此处了解有关
Razor 页面中选择列表的基础知识的更多信息。
Javascript
document.getElementById("btnSave").addEventListener("click", (e) => {
// Select all, so model binder will make all options available in c#.
$("#selectedIds").find("option").each(function () {
$(this).prop('selected', true);
});
});