我在列表框中预选项目时遇到了问题。我使用razor视图引擎与mvc 3。我知道有几个帖子有同样的问题,但它们不适合我。
类中的代码:
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;
}
我猜它与能够跨请求持久化有关(请求将被扁平化为字符串以通过网络传递),但这有点令人困惑!
在MVC5中,您可以直接使用ListBoxFor与多选。请确保在加载视图时,selectedItem应该有一个项目列表。
@Html.ListBoxFor(m => m.SelectedItem, new MultiSelectList(Model.Item.ToList(), "Value", "Text"), new { @class = "form-control" })