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 に答える