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

741 Views Asked by At

I want to grab all the values of a multiple selected selectlist but it keeps telling me null. this is my viewmodel

 public class ImportFromStaffListVM
    {

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

select tag is

     @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();
                }

anytime i run the controller it tells me null. Please any help is appreciated

1

There are 1 best solutions below

1
Stewart On

I think you've got a bit confused with the implementation. Have a look at the multi select example in the online documentation. https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-6.0#the-select-tag-helper If you compare your code with that example, it should help you resolve.

Having a quick compare myself I think the StaffId property needs to be a list in your model. Since you're selecting multiple StaffIds.

IEnumerable<string> StaffId

Then you actually loop through the StaffId list in your Action method to get the selected StaffIds.

Note: You don't need the id="selectUser" also, since the asp-for will give the generated html an id="StaffId"