使用ViewBag填充自定义文本的下拉列表

时间:2015-12-15 09:53:48

标签: c# asp.net-mvc linq linq-to-sql viewbag

我使用ViewBag填充Dropdown,如下所示:

控制器:

ViewBag.bolumList = db.SbtBolum.OrderBy(s => s.BolumAd)

查看:

@Html.DropDownListFor(model => model.YGKisiBolum.Bolum, new     SelectList(ViewBag.bolumList, "BolumID" , "BolumAd"), "Seçiniz", new { @class = "form-control" })

现在我想在文本字段中显示组合的两列,如SQL:

SELECT BolumID As Value, BolumAd+" "+BolumExtra AS Text FROM SbtBolum

如何使用ViewBag和Linq执行此操作?

1 个答案:

答案 0 :(得分:4)

var values = db.SbtBolum.OrderBy(s => s.BolumAd).ToList().Select(s => SelectListItem
{
    Value = s.BolumID.ToString(),
    Text = s.BolumAd + " " + s.BolumExtra,
});
ViewBag.bolumList = values;

并在您看来:

@Html.DropDownListFor(
    model => model.YGKisiBolum.Bolum, 
    (IEnumerable<SelectListItem>)ViewBag.bolumList, 
    "Seçiniz", 
    new { @class = "form-control" }
)

据说/显示,我完全建议不要这样做。我宁愿使用强类型视图模型来摆脱ViewBag。