MVC 5 下拉列表用于编辑视图中的多选值绑定

MVC 5 Dropdownlistfor multiselect value binding in edit view

我在编辑视图中有一个 select2 多选下拉列表。当我尝试将选定值绑定到下拉列表时,它无法绑定。任何帮助表示赞赏。请从 *.cshtml 和 *.cs 文件中找到以下代码片段。

@Html.DropDownListFor(model => model.Items, new MultiSelectList(ViewBag.ItemsBag, "Value", "Text", Model.ItemsSelected.Select(x => x.Value)), new { @class = "form-control features-segments select2-multiselect-checkbox", multiple = "multiple" })

ViewBag.ItemsBag = db.Items.Select(v => new SelectListItem
            {
                Text = v.ItemName,
                Value = v.ItemId.ToString()
            });

ModelVM modelVM = new ModelVM()
            {
                ItemsSelected = SelectedItems.Items.Select(x => new SelectListItem() { Text = x.ItemName, Value = x.ItemId.ToString() })
            };

物品模型有以下物品。 属性 ItemsSelected 不为空,其中包含 3 个值,ViewBag.ItemsBag 也不为空,并且包含数据库中的所有项目。这两个 属性 都是 SelectListItem 类型,具有 Text 和 Value 属性。

public int FeatureId { get; set; }
public string FeatureName { get; set; }
public string ReferenceName { get; set; }
public FeatureSection SectionName { get; set; }//Enum
public FeatureType Type { get; set; }//Enum
public bool DefaultBoolValue { get; set; }
public string DefaultTextValue { get; set; }
public IEnumerable<SelectListItem> ItemsSelected { get; set; }
public virtual ICollection<Item> Items { get; set; } = new List<Item>();

由于您在 ViewBag 定义中提供了项目值,这清楚地表明了字符串值:

ViewBag.ItemsBag = db.Items.Select(v => new SelectListItem
{
    Text = v.ItemName,
    Value = v.ItemId.ToString() // implies all values are strings
});

然后 属性 与 DropDownListFor/ListBox 绑定必须具有 List<string>string[] 类型才能正确绑定。使用 ICollection<Item> 不会绑定,因为它是一个复杂的对象,而 helper 需要值类型(数字 types/string)来绑定。

因此,您必须首先创建类型为 List<string> 的 属性:

public List<string> SelectedValues { get; set; }

然后使用 ListBoxFor 帮助程序代替 属性:

@Html.ListBoxFor(model => model.SelectedValues, new MultiSelectList(ViewBag.ItemsBag, "Value", "Text", Model.ItemsSelected.Select(x => x.Value)), new { @class = "form-control features-segments select2-multiselect-checkbox", multiple = "multiple" })

注:

如果 ItemId 属性 具有 int 类型(并且所有值都可转换为 int),请尝试使用 List<int>/int[]输入而不是 List<string>/string[]:

public List<int> SelectedValues { get; set; }

请在 jQuery 的文档就绪状态下尝试以下代码:

var result = [1,3,5];// Array of SelectedValues
$("#DropdownID").val(result); // DropdownID = your multi select dropdown Id