How to pass multiselect list's selected Items back to controller?

前端 未结 1 1864
长情又很酷
长情又很酷 2020-12-18 07:49

I am developing a MVC application which contains the multiselect dropdown list. I want to get the ID\'s of multiple selected items of the drop down.

I have the code

相关标签:
1条回答
  • 2020-12-18 08:47

    Using a wrapper model with a property to bind the selected customers to works (I tried it):

    Wrapper Model:

    public class CustomerList
    {
        public List<Customer> Customers { get; set; }
        public List<int> SelectedIDs { get; set; }
    }
    

    Controller:

            [HttpGet]
            public ActionResult DisplayCustomer()
            {
                Customer oCustomer = new Customer();
                List<Customer> CustomersList = new List<Customer>();
                CustomersList.Add(new Customer() { ID = 1, Name = "TestCustomer1", Amt = 123 });
                CustomersList.Add(new Customer() { ID = 2, Name = "TestCustomer2", Amt = 234 });
                CustomersList.Add(new Customer() { ID = 3, Name = "TestCustomer3", Amt = 324 });
                ViewBag.CustList = CustomersList;
                return View(new CustomerList() { Customers = CustomersList }); 
    
            }
    
            [HttpPost]
            public void DisplayCustomer(List<int> selectedIds)
            {
                // do something with the id list
            }
    

    View:

    @model MvcApplication2.Models.CustomerList
    
    @using (Html.BeginForm(@Model.SelectedIDs))
    {
        @Html.ListBoxFor(m => m.SelectedIDs, new MultiSelectList(@Model.Customers, "ID", "Name", @Model.SelectedIDs))
        <input type="submit" value="save" />
    }
    

    You need something to bind your selection to and send it back to the controller.

    0 讨论(0)
提交回复
热议问题