5

我的操作中有以下代码:

        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# 中做到这一点。

4

1 回答 1

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);

在您看来:

@Html.DropDownList("AccountID", ViewBag.AccountIdList)

请注意,无需添加,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);
于 2012-05-02T18:48:05.650 回答