ASP.NET MVC ListBox does not show the selected list items

回眸只為那壹抹淺笑 提交于 2019-12-02 04:14:43

You cannot bind a <select multiple> to a collection of complex objects. It binds to, and posts back an array of simple values (the values of the selected options).

Your SelectedCompanies property needs to be IEnumerable<int> (assuming the CompanyId of Company is also int). Note also the Selected property of SelectListItem is ignored when binding to a property.

Your also using the same collection for the selected Companies and the list of all Companies which makes no sense. Your SelectListCompanies should be generated from your table of Company.

Model

public class MyViewModel
{
     public IEnumerable<int> SelectedCompanies { get; set; }
     public IEnumerable<SelectListItem> SelectListCompanies { get; set; }
}

Base on your current code for EditableModel, your code should be

public ActionResult Edit(int id)
{
    var service = _serviceDAL.GetEditableModel(id);
    ....
    MyViewModel model = new MyViewModel
    {
        SelectedCompanies = service.SelectedCompanies.Select(x => x.CompanyId),
        SelectListCompanies = GetSelectListCompanies()
    };
    return View(model);

private IEnumerable<SelectListItem> GetSelectListCompanies()
{
    var all companies = ... // call method to get all Companies
    return companies.Select(x => new SelectListItem
    {
        Value = x.CompanyId.ToString(),
        Text = x.Name
    });
}

However, it look like you should be modifying your EditableModel and the GetEditableModel() code to return the correct data in the first place.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!