MVC ListBox mutiple selects only one value in the controller per post

I followed the instructions for the list and tried to process the selections correctly. What throws me and I can’t find the right material is access to the selected values. There can be only one selected, but most likely there will be several selected at a time.

my postcontroller receives the object model and does it matter one of the selected elements, but not all of them? Should I run some jquery before post, as other articles have said? It seems wrong, but maybe ...

My model:

public partial class ExtrnlSubsModel : BaseEntityModel
{
    public IList<SelectListItem> AvailableForums { get; set; }
    public int ExtForumId { get; set; }
}

My razor:

@Html.ListBoxFor(model => model.ExtForumId, Model.AvailableForums, new { style = "width:500px;height:250px" })
@Html.RequiredHint()
@Html.ValidationMessageFor(model => model.ExtForumId)

My controller:

[HttpPost]
public ActionResult ExtForumAdd(ExtrnlSubsModel model)
{ .... }

So, as I mentioned, my model is populated, but with only one choice, despite the ctrl-clicked multiple elements.

TIA

+4
1

MultiSelect int , ( ):

public class ExtrnlSubsModel
{
    public MultiSelectList AvailableForums { get; set; }
    public int[] ExtForumIds { get; set; }
}

, ints:

@Html.ListBoxFor(model => model.ExtForumIds, Model.AvailableForums, new { style = "width:500px;height:250px" })

:

public ActionResult Index()
{       
        var items = new List<SelectItem>();
        // These items would be set from your db
        var items = new List<SelectItem>();
        items.Add(new SelectItem { Id = 1, Name = "1" });
        items.Add(new SelectItem { Id = 2, Name = "2" });

        var selectedItems = new List<SelectItem>();
        selectedItems.Add(new SelectItem { Id = 1, Name = "1" });

        var model = new ExtrnlSubsModel();
        // project the selected indexs to an array of ints
        int[] selectedItemsArray = selectedItems.Select(s => s.Id).ToArray();
        model.ExtForumIds = selectedItemsArray;
        model.AvailableForums = new MultiSelectList(items, "ID", "Name", selectedItemsArray);

    return View(model);
}

:

[HttpPost]
public ActionResult Index(ExtrnlSubsModel model)
{
    var selectedItems = model.ExtForumIds;
    return View(model);
}

SelectItem , , :

public class SelectItem
{
    public int Id { get; set; }
    public string Name { get; set; }
}

, :

Screen grab

+5

Source: https://habr.com/ru/post/1527320/


All Articles