Tob*_*ias 18 .net asp.net-mvc razor asp.net-mvc-3
我在列表框中预选项目时遇到问题.我正在使用带有mvc 3的剃刀视图引擎.我知道有一些帖子有同样的问题,但它们对我不起作用.
课程代码:
public class Foo{
private int _id;
private string _name;
public string Name{
get{
return _name;
}
public int Id {
get{
return _id;
}
}
Run Code Online (Sandbox Code Playgroud)
型号代码:
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;}
}
}
Run Code Online (Sandbox Code Playgroud)
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"})
Run Code Online (Sandbox Code Playgroud)
我尝试了很多其他的东西,但没有任何效果.希望有人能提供帮助.
Dan*_*eny 31
我无法解释原因,但我设法让它发挥作用.这些都有效:
@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"})
Run Code Online (Sandbox Code Playgroud)
问题似乎是忽略SelectListItem上的Selected属性,而是ToString()调用(!)方法,所以如果你需要将它添加到你的Foo类:
public override string ToString()
{
return this.ID;
}
Run Code Online (Sandbox Code Playgroud)
我猜它与能够持续跨越请求(它将被平铺到字符串以通过线路传递)有关,但它有点令人困惑!
| 归档时间: |
|
| 查看次数: |
28633 次 |
| 最近记录: |