我的控制器中有以下代码。请注意,如果companyId为4,我希望它是我的下拉列表中的默认值:
Movie
视图内容:
var company = _conpanyService.companyLst().ToList();
var items = new List<SelectListItem>();
foreach (var item in company)
{
items.Add(new SelectListItem()
{
Text = item.CompanyName,
Value = item.CompanyID.ToString(),
Selected = item.CompanyID == 4 ? true : false
});
}
// I double checked the items list and it does have companyID of 4 set to Select to true. Not sure why it did not propagate to the view.
ViewBag.CompanyList = items;
问题在于,即使我在View上查看源代码,所选内容也不会通过。我不确定为什么没有选择它。
答案 0 :(得分:0)
尝试一下。在控制器中,
var company = _conpanyService.companyLst().ToList();
ViewBag.CompanyList = new SelectList(company, "CompanyId", "CompanyName", 4);
在视图中,
@Html.DropDownList("CompanyId", (SelectList) ViewBag.CompanyList)