How can I create my own SelectList with values ​​"00" and "" in C # for MVC?

There is the following code in my action:

        ViewBag.AccountId = new SelectList(_reference.Get("01")
            .AsEnumerable()
            .OrderBy(o => o.Order), "RowKey", "Value", "00");

and, in my opinion:

@Html.DropDownList("AccountID", null, new { id = "AccountID" })

Now I would like to create a list dynamically, so in my action I would just like to rigidly select a simple SelectList with the values: 00 and "", so that when I go to my view I see only an empty selection field.

Can someone explain how I can do this in C #.

+5
source share
1 answer

In your controller:

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

In your opinion:

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

Please note: there is no need to add new { id = "AccountId" }, since MVC will give this identifier in any case.

Edit:

, , ?

, ( ):

List<SelectListItem> items = new List<SelectListItem>();

var emptyItem = new SelectListItem(){
    Value = "",
    Text  = "00"
};

items.Add(emptyItem);

ViewBag.AccountIdList = new SelectList(items);
+12

All Articles