我的行动中有以下代码:
ViewBag.AccountId = new SelectList(_reference.Get("01")
.AsEnumerable()
.OrderBy(o => o.Order), "RowKey", "Value", "00");
Run Code Online (Sandbox Code Playgroud)
在我看来:
@Html.DropDownList("AccountID", null, new { id = "AccountID" })
Run Code Online (Sandbox Code Playgroud)
现在我想动态创建列表,所以在我的动作中,我只想用一个简单的SelectList进行硬编码,其值为:00和"",这样当我进入我的视图时,我只看到一个空白的选择框.
有人可以解释我如何在C#中做到这一点.
Oma*_*mar 12
在你的控制器中:
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);
Run Code Online (Sandbox Code Playgroud)
在你看来:
@Html.DropDownList("AccountID", ViewBag.AccountIdList)
Run Code Online (Sandbox Code Playgroud)
注意,不需要添加,new { id = "AccountId" }因为MVC无论如何都会给ID控制.
编辑:
如果您只需要一个空的下拉列表,为什么要在控制器中创建一个非空的选择列表?
无论如何,这是你可以做的(视图代码保持不变):
List<SelectListItem> items = new List<SelectListItem>();
var emptyItem = new SelectListItem(){
Value = "",
Text = "00"
};
items.Add(emptyItem);
ViewBag.AccountIdList = new SelectList(items);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17982 次 |
| 最近记录: |