gpt4 book ai didi

.net - 预选多选列表框中的项目 (MVC3 Razor)

转载 作者:行者123 更新时间:2023-12-03 02:53:08 25 4
gpt4 key购买 nike

我在列表框中预选项目时遇到问题。我正在使用带有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com