列表框中预选项目

列表框中预选项目

我在列表框中预选项目时遇到问题。
我在MVC 3中使用razor view engine。我知道有一些帖子有同样的问题,但是它们对我不起作用。

班级代码:

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

    public string Name{
       get{
           return _name;
       }

    public int Id {
       get{
           return _id;
       }

}


模型中的代码:

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

}


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


我尝试了许多其他事情,但没有任何效果。希望有人能帮忙。

最佳答案

我无法真正解释为什么,但是我设法使它起作用。这些方法均有效:

@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"})


问题似乎是SelectListItem上的Selected属性被忽略,而是调用了ToString()(!)方法,因此,如果需要将其添加到您的Foo类中:

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


我猜想这与能够跨请求保留(将被展平为要通过电线传递的字符串)有关,但这有点令人困惑!

10-08 11:58