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
510 views
in Technique[技术] by (71.8m points)

.net - Preselect Items in Multiselect-Listbox (MVC3 Razor)

I have a problem with the preselection of Items in a listbox. I am using razor view engine with mvc 3. I know there are a few posts with the same issue but they don't work for me.

Code in Class:

public class Foo{
    private int _id;
    private string _name;

    public string Name{
       get{
           return _name;
       }

    public int Id {
       get{
           return _id;
       }

}

Code in Model:

public class FooModel{

    private readonly IList<Foo> _selectedFoos;
    private readonly IList<Foo> _allFoos;

    public IList<Foo> SelectedFoos{
         get{ return _selectedFoos;}
    }

    public IList<Foo> AllFoos{
         get{ return _allFoos;}
    }

}

Code in cshtml:

 @Html.ListBoxFor(model => model.Flatschels, 
        Model.AllFlatschels.Select(fl => new SelectListItem {
             Text = fl.Name,
             Value = fl.Id.ToString(),
             Selected = Model.Flatschels.Any(y => y.Id == fl.Id)
   }), new {Multiple = "multiple"}) 

I tried lots of other things but nothing worked. Hope someone can help.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I can't really explain why, but I managed to get it working. Either of these worked:

@Html.ListBoxFor(m => m.SelectedFoos,
            new MultiSelectList(Model.AllFoos, "ID", "Name"), new {Multiple = "multiple"}) 

@Html.ListBoxFor(m => m.SelectedFoos, Model.AllFoos
            .Select(f => new SelectListItem { Text = f.Name, Value = f.ID }),
                new {Multiple = "multiple"}) 

The problem seems to be that the Selected property on SelectListItem is ignored, and instead the ToString()(!) method is being called, so if you need to add this to your Foo class:

public override string ToString()
{
    return this.ID;
}

I'm guessing it has something to do with being able to persist across requests (which will be flattened to strings to be passed over the wire), but it's a bit confusing!


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

...