我有這個幫手。現在,這不是我的。這是爲了顯示和填充下拉菜單。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