本文介绍了SelectedValues​​不MultiSelectList MVC工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像

 public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Category> CategorySelected { get; set; }
        public static List<Category> GetOptions()
        {
            var categories = new List<Category>();
            categories.Add(new Category() {  ID = 1, Name = "Bikes" });
            categories.Add(new Category() {  ID = 2, Name = "Cars" });
            categories.Add(new Category() {  ID = 3, Name = "Trucks" });

            return categories;
        }
    }

在控制器我填写MiltiselectItems并为它设置selectedValues​​

In the controller I Fill MiltiselectItems and set selectedValues for it

 public ActionResult Index()
    {
       Category cat=new Category();
       cat.CategorySelected.Add(new Category { ID =1, Name = "Bikes" });
       cat.CategorySelected.Add(new Category { ID =3, Name = "Trucks" });

        var list = Category.GetOptions();
        product.Categories = new MultiSelectList(list, "ID", "Name", CategorySelected);
    }

在查看code我有

@Html.ListBox("Category", Model.Categories)

在运行我的行动SelectedValues​​不工作。我做错了吗?

when run my action SelectedValues aren't working. What I'm doing wrong ?

推荐答案

MultiSelectList 构造函数的最后一个参数需要选择标识的数组的不类别复杂类型的集合。

The last parameter of the MultiSelectList constructor takes an array of selected Id's not a collection of Category complex types.

如果您将其更改为这个代替它会如预期:

If you change it to this instead it will work as expected:

product.Categories = new MultiSelectList(list, "ID", "Name", cat.CategorySelected.Select(c => c.ID).ToArray());

它只是项目入标识的替代。

请参见下面的屏幕截图:

See below screen shot:

诗我也不得不把它添加到类别的构造函数初始化集合:

Ps I also had to add this to the constructor of Category to initialize the collection:

public Category()
{
   CategorySelected = new List<Category>();
}

这篇关于SelectedValues​​不MultiSelectList MVC工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 16:38