我有这个帮手。现在,这不是我的。这是为了显示和填充下拉菜单。dropdownlistfor未选择页面加载时应该选择什么
public static IEnumerable<SelectListItem> ToSelectList<T, TTextProperty, TValueProperty>(this IEnumerable<T> instance, Func<T, TTextProperty> text, Func<T, TValueProperty> value, Func<T, bool> selectedItem = null)
{
return instance.Select(t => new SelectListItem
{
Text = Convert.ToString(text(t)),
Value = Convert.ToString(value(t)),
Selected = selectedItem != null && selectedItem(t)
});
}
然后,我有这些类:
public class FooVm {
public FooVm() {
Bars = new HashSet<BarVm>();
}
public int FooId { get; set; }
public IEnumerable<BarVm> Bars { get; set; }
}
public class BarVm {
public int BarId { get; set; }
public int BarName { get; set; }
}
然后有这个LINQ查询:
var fooBar = _db.Foo
.WithId(fooId)
.Select(f => new FooVm {
FooId = f.Id,
Bars = f.Bars.Select(b => new BarVm {
BarId = b.Id,
BarName = b.Name
})
})
.ToList();
ViewBag.Bars = _db.Bars
.ToSelectList(s => s.Name, s => s.Id);
然后,当我试图使这些结果进行编辑/更新。
@model ViewModels.Foo.FooVm
@Html.LabelFor(model => model.FooId)
@foreach(var item in Model.Bars) {
@Html.DropDownListFor(model => item.BarId, ViewBag.Bars as IEnumerable<SelectListItem>, "Select bar")
}
下拉列表呈现正常,但没有选择页面加载时应该选择的内容。
我错过了什么?任何帮助将非常感激。谢谢
这个帮助器的实际点是什么(与使用'SelectList'构造器之一相反 - 例如'new SelectList(_db.Bars,“BarId”,“BarName”)''而且'foreach'循环没有有道理 - 你会生成重复的'id'属性(无效的html)和重复的'name'属性,这些属性不会绑定到与你的模型相关的任何东西上 – 2015-04-06 02:50:30
@StephenMuecke非常感谢你,不知道我可以做那样的事情。 – 2015-04-06 16:20:57