我的操作中有以下代码:
ViewBag.AccountId = new SelectList(_reference.Get("01")
.AsEnumerable()
.OrderBy(o => o.Order), "RowKey", "Value", "00");
在我看来:
@Html.DropDownList("AccountID", null, new { id = "AccountID" })
现在我想动态创建列表,因此在我的操作中,我只想用值硬编码一个简单的 SelectList:00 和“”,这样当我进入视图时,我只看到一个空白选择框。
有人可以解释一下我如何在 C# 中做到这一点吗?
在你的控制器中:
var references = _reference.Get("01").AsEnumerable().OrderBy(o => o.Order);
List<SelectListItem> items = references.Select(r =>
new SelectListItem()
{
Value = r.RowKey,
Text = r.Value
}).ToList();
var emptyItem = new SelectListItem(){
Value = "",
Text = "00"
};
// Adds the empty item at the top of the list
items.Insert(0, emptyItem);
ViewBag.AccountIdList = new SelectList(items);
在您看来:
@Html.DropDownList("AccountID", ViewBag.AccountIdList)
注意,不需要添加new { id = "AccountId" }
因为 MVC 无论如何都会给控件该 ID。
Edit:
如果您只需要一个空的下拉列表,为什么要在控制器中创建一个不为空的选择列表?
无论如何,您可以执行以下操作(查看代码保持不变):
List<SelectListItem> items = new List<SelectListItem>();
var emptyItem = new SelectListItem(){
Value = "",
Text = "00"
};
items.Add(emptyItem);
ViewBag.AccountIdList = new SelectList(items);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)