2013-04-09 20 views
5
class User() { 
    public List<Customer> Customers; 
} 

class Customer() { 
    public long Id; 
    public string Name; 
} 

显示多选列表我填写所选项目如何从列表<MyObject>

User MyUser = new User(); 
MyUser.Customers = db.Customers.Where(...).ToList(); 

我通过这种方式

ViewBag.Customers = db.Customers.OrderBy(c => c.Name).ToList(); 

在我看来,我希望所有的项目清单将其显示为多选HTML元素,其中包含所有(ViewBag.Customers)元素和(MyUser.Customers)选定的元素。 我试着用

@model MySCL.Models.User 

@Html.ListBoxFor(m => m.Customers, new MultiSelectList(ViewBag.Customers, "Id", "Name"), new {Multiple = "multiple", size = "5" }) 

,但只显示没有选择任何项目的完整列表。 这是最好的做法吗? 还有更好的方法吗? 如果我有一个字符串列表,而不是客户列表,我该怎么做?

+1

里克·安德森知道的伎俩http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with -aspnet -mvc – Komengem 2013-04-09 16:14:03

回答

1

MultiSelectList constructor也需要项目的IEnumerable列表中进行选择,因此,如果你改变你的代码:

new MultiSelectList(ViewBag.Customers, "Id", "Name", Model.Customers) 

列表,然后应与客户选择的所有项目启动。

+0

我想从列表中选择所有项目(包含所有客户的ViewBag.Customers)和(MyUser.Customers是ViewBag.Customers的一个子集)开始。 – whiteproud 2013-04-10 08:20:37

+0

然后第四个参数变成Model.Customers。 – 2013-04-10 14:58:15

1

我通过将第四个参数作为int或string列表传递给对象唯一键而不是对象列表来解决。

new MultiSelectList(ViewBag.Customers, "Id", "Name", Model.Customers.Select(c => c.Id))