作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在列表框中预选项目时遇到问题。我正在使用带有 mvc 3 的 razor View 引擎。我知道有一些帖子有同样的问题,但它们对我不起作用。
类中的代码:
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;
}
我猜这与能够跨请求持久存在有关(它将被展平为通过线路传递的字符串),但这有点令人困惑!
关于.net - 预选多选列表框中的项目 (MVC3 Razor),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5858679/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!