简体   繁体   English

列表框中的多个默认选定项

[英]Multiple default selected items in Listbox

I'm looking into creating an Edit page for a Company object that has multiple categories (that are predefined in a list). 我正在考虑为具有多个类别(在列表中预定义)的Company对象创建一个Edit页面。 I have the list being sent through the ViewBag, and have the categories that the user selected in the Create page in an Array thanks to a ViewModel. 我具有通过ViewBag发送的列表,并且由于ViewModel而具有用户在“数组”的“创建”页面中选择的类别。

I can't figure out a way to have the ListBox prepopulate with the multiple values in my array. 我想不出一种方法来让ListBox预先填充数组中的多个值。 I was playing around with jQuery and was able to get one of the values to be selected, but when I try more than one nothing shows up. 我正在玩jQuery,并且能够获得要选择的值之一,但是当我尝试多个时,什么都没有显示。 Any ideas? 有任何想法吗?

@Html.ListBox("Category", new SelectList(ViewBag.Category, "Text", "Value"))

The SelectListItem object has a Selected property to indicate this. SelectListItem对象具有Selected属性来表明这一点。 So I guess it would come down to how you build the SelectList . 所以我想这将SelectList您如何构建SelectList Currently you do this: 目前,您正在执行以下操作:

new SelectList(ViewBag.Category, "Text", "Value")

Which works, but gives you no control over the individual SelectListItem s. 哪个可行,但使您无法控制各个SelectListItem Instead of building a SelectList , you can build an IEnumerable<SelectListItem> using the same method overload . 除了构建SelectList ,您还可以使用相同的重载方法来构建IEnumerable<SelectListItem> Initially that might look like this: 最初可能看起来像这样:

ViewBag.Category.Select(c => new SelectListItem
{
    Text = c.Text,
    Value = c.Value
});

At this point you have more control over the individual items. 此时,您可以更好地控制各个项目。 Now it's just a matter of determining which ones should be selected. 现在,只需确定应选择哪些选项即可。 How do you determine that? 您如何确定? Is it a property on the Category object? 它是Category对象的属性吗? Something like this?: 像这样吗?

ViewBag.Category.Select(c => new SelectListItem
{
    Text = c.Text,
    Value = c.Value,
    Selected = c.Selected
});

Or perhaps some other condition?: 还是其他条件?:

ViewBag.Category.Select(c => new SelectListItem
{
    Text = c.Text,
    Value = c.Value,
    Selected = c.SomeValue == SomeCondition
});

How you determine that is up to you, and ideally something you can logically add to the backing model being used here. 如何确定取决于您自己,理想情况下可以在逻辑上添加到此处使用的支持模型中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM