本文介绍了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);
    }

在查看代码中我有

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

运行时我的操作 SelectedValues 不起作用.我做错了什么?

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

推荐答案

MultiSelectList 构造函数的最后一个参数采用所选 Id 的数组,而不是Category 复杂类型.

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());

它只是将其投影到 Id 的数组中.

It simply projects it into an array of Id's instead.

见下面的屏幕截图:

Ps 我还必须将它添加到 Category 的构造函数中以初始化集合:

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 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 00:33