How can I create my own SelectList with values of “00” and “” in C# for MVC?

痞子三分冷 提交于 2021-02-20 13:32:08

问题


I have the following code in my action:

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

and in my view:

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

Now I would like to create the list dynamically so in my action I would just like to hardcode a simple SelectList with the values: 00 and "" so that when I go to my view I see just a blank select box.

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


回答1:


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 view:

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

Note, no need to add new { id = "AccountId" } since MVC will give the control that ID anyway.

Edit:

If you only need an empty drop down list why are you creating a select list that isn't empty in your controller?

Anyway, here's what you can do (the view code remains the same):

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

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

items.Add(emptyItem);

ViewBag.AccountIdList = new SelectList(items);


来源:https://stackoverflow.com/questions/10419709/how-can-i-create-my-own-selectlist-with-values-of-00-and-in-c-sharp-for-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!