我希望能够编辑选择菜单项的显示文本。我仍然希望选择菜单将来自Traveler的Id作为值,将Name作为显示值。但是,我想在我的Traveler模型中将该显示值与名为destination
的不同列连接起来 SelectList TravelersList = new SelectList(db.Travelers.Where(c => c.TravelerId == ThisId), "Id", "Name");
foreach(var item as TravelersList)
{
//Concatenate the Traveler Name with the Destination
}
ViewBag.Travelers = TravelersList;
答案 0 :(得分:1)
您需要使用SelectList
生成.Select()
并将值投影到SelectListItem
IEnumerable<SelectListItem> TravelersList = db.Travelers
.Where(c => c.TravelerId == ThisId).AsEnumerable().Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = string.Format("{0} {1}", x.Name, x.Destination)
});
ViewBag.Travelers = TravelersList;
在视图中,它将是
@Html.DropDownListFor(m => m.someProperty, (IEnumerable<SelectListItem>)ViewBag.Travelers, ...)
虽然我建议您使用包含属性IEnumerable<SelectListItem> Travelers
的视图模型,以便视图为@Html.DropDownListFor(m => m.someProperty, Model.Travellers, ...)