.net 多选列表框中的预选项目 (MVC3 Razor)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5858679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Preselect Items in Multiselect-Listbox (MVC3 Razor)
提问by Tobias
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.
我在列表框中预选项目时遇到问题。我正在使用带有 mvc 3 的 razor 视图引擎。我知道有一些帖子有同样的问题,但它们对我不起作用。
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:
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.
我尝试了很多其他的东西,但没有任何效果。希望有人能帮忙。
回答by Danny Tuppeny
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 Fooclass:
问题似乎是 SelectListItem 上的 Selected 属性被忽略,而是ToString()调用了(!) 方法,因此如果您需要将其添加到您的Foo类中:
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!
我猜这与能够跨请求持久化有关(这将被扁平化为要通过线路传递的字符串),但这有点令人困惑!
回答by John Kuriakose
In MVC5 you can directly use ListBoxFor with multiselect. Make sure while loading the view your selectedItem should have list of items.
在 MVC5 中,您可以直接将 ListBoxFor 与多选一起使用。确保在加载视图时您的 selectedItem 应该有项目列表。
@Html.ListBoxFor(m => m.SelectedItem, new MultiSelectList(Model.Item.ToList(), "Value", "Text"), new { @class = "form-control" })

