Get selected values from a select list RRS feed

  • Question

  • User-29703693 posted

    I'm generating a select list using:

    <select asp-for="Participants" asp-items="Model.SelectOptions" multiple>
    [Required(ErrorMessage = "* select at least one")]
    public SelectList Participants { get; set; }
    public List<SelectListItem> SelectOptions { get; set; }

    OnPost I'd like to loop through all the selected items in the selectlist but when I try: 

    foreach (SelectListItem participant in Participants)
                    if (participant.Selected)

    I get the error: 

    InvalidOperationException: Could not create an instance of type 'Microsoft.AspNetCore.Mvc.Rendering.SelectList'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Record types must have a single primary constructor. Alternatively, set the 'Participants' property to a non-null value in the 'ncswLearn2.Pages.Training.IndexModel' constructor.

    So how should I loop through all of the selected values?  I'm assuming there's a simple solution, but after googling for a bit I couldn't find the answer.  Thanks in advance

    Friday, December 4, 2020 8:48 PM


  • User475983607 posted

    You misunderstand basic HTML forms.  The browser submits the selected options not all the options.  The MVC model binder expects the same behavior.  This concept is covered in every beginning level tutorial.

    <form method="post">
        <select name="Participants" multiple>
            <option value="">--Select--</option>
            <option value="1">Item 1</option>
            <option value="2">Item 2</option>
            <option value="3">Item 3</option>
            <option value="4">Item 4</option>
        <input id="Submit1" type="submit" value="submit" />
    public IActionResult Index()
        return View();
    public IActionResult Index(int[] Participants)
        return Json(Participants);

    Example values

    [1, 3]


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 4, 2020 9:13 PM