繁体   English   中英

我如何在 asp.net 核心 mvc 中获取多个选择列表的所有值

[英]How do i get all the values of multiple selectlist in asp.net core mvc

我想获取多选选择列表的所有值,但它一直告诉我 null。这是我的视图模型

 public class ImportFromStaffListVM
    {

        public string StaffId { get; set; }
        public SelectList StaffList {get;set;}
        
    }

select 标签是

     @using (Html.BeginForm("ImportFromStaffList", "Training", FormMethod.Post))
            {

                <div class="card">
                    <div class="card-header">
                        <h5>Add Participants</h5>
                        <!--<span>Add class of <code>.form-control</code> with <code>&lt;input&gt;</code> tag</span>-->
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <select type="text" id="selectUser" data-width="100%" class=" select2 form-control" asp-items="@Model.StaffList" asp-for="@Model.StaffId" multiple="multiple"></select>

                        </div>
  public async Task < IActionResult>  ImportFromStaffList(ImportFromStaffListVM importFromStaffListVM)
        {
           
            foreach (var staff in  importFromStaffListVM.StaffList.Where(x => x.Selected).Select(y => y.Value).ToList())
            {

          var      selectedStaff = dcx.StaffList.Where(x => x.StaffId.Contains(staff.ToString())).ToList();

                foreach (var staffid in selectedStaff)
                {
                    Participant newParticipant = new Participant()
                    {
                        DateOfBirth = staffid.DateOfBirth,
                        Contact = staffid.Contact,
                        Name = staffid.Name,
                        Rank = staffid.Rank,
                        Department = staffid.Department,
                    };

                    dcx.Participants.Add(newParticipant);
                    await dcx.SaveChangesAsync();
                }

任何时候我运行 controller 它都会告诉我 null。请提供任何帮助,我们将不胜感激

我认为您对实施有些困惑。 查看在线文档中的 multi select 示例。 https://learn.microsoft.com/en-us/as.net/core/mvc/views/working-with-forms?view=as.netcore-6.0#the-select-tag-helper如果你比较你的代码用那个例子,它应该可以帮助你解决。

快速比较一下我自己,我认为 StaffId 属性需要是您的 model 中的一个列表。因为您选择了多个 StaffId。

IEnumerable<string> StaffId

然后,您实际上在 Action 方法中循环遍历 StaffId 列表以获取选定的 StaffId。

注意:您也不需要 id="selectUser",因为 asp-for 将为生成的 html 提供一个 id="StaffId"

暂无
暂无

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

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