Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

c# - SelectedValues not working in MultiSelectList mvc

I have a class like

 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;
        }
    }

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

In View Code I have

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

See below screen shot:

Screen grab

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...