How can I add an item to a SelectList in ASP.net M

2020-01-27 12:55发布

Basically I am looking to insert an item at the beginning of a SelectList with the default value of 0 and the Text Value of " -- Select One --"

Something like

SelectList list = new SelectList(repository.func.ToList());
ListItem li = new ListItem(value, value);
list.items.add(li);

Can this be done?

13条回答
Ridiculous、
2楼-- · 2020-01-27 13:21

The .ToList().Insert(..) method puts an element into your List. Any position can be specified. After ToList just add .Insert(0, "- - First Item - -")

Your code

SelectList list = new SelectList(repository.func.ToList());
ListItem li = new ListItem(value, value);
list.items.add(li);

New Code

SelectList list = new SelectList(repository.func.ToList().Insert(0, "- - First Item - -"));
ListItem li = new ListItem(value, value);
list.items.add(li);
查看更多
Summer. ? 凉城
3楼-- · 2020-01-27 13:22

This is possible.

//Create the select list item you want to add
SelectListItem selListItem = new SelectListItem() { Value = "null", Text = "Select One" };

//Create a list of select list items - this will be returned as your select list
List<SelectListItem> newList = new List<SelectListItem>();

//Add select list item to list of selectlistitems
newList.Add(selListItem);

//Return the list of selectlistitems as a selectlist
return new SelectList(newList, "Value", "Text", null);
查看更多
可以哭但决不认输i
4楼-- · 2020-01-27 13:23

Okay I like clean code so I made this an extension method

static public class SelectListHelper
{
    static public SelectList Add(this SelectList list, string text, string value = "", ListPosition listPosition = ListPosition.First)
    {
        if (string.IsNullOrEmpty(value))
        {
            value = text;
        }
        var listItems = list.ToList();
        var lp = (int)listPosition;
        switch (lp)
        {
            case -1:
                lp = list.Count();
                break;
            case -2:
                lp = list.Count() / 2;
                break;
            case -3:
                var random = new Random();
                lp = random.Next(0, list.Count());
                break;
        }
        listItems.Insert(lp, new SelectListItem { Value = value, Text = text });
        list = new SelectList(listItems, "Value", "Text");
        return list;
    }

    public enum ListPosition
    {
        First = 0,
        Last = -1,
        Middle = -2,
        Random = -3
    }
}

Usage (by example):

var model = new VmRoutePicker
    {
     Routes =
     new SelectList(_dataSource.Routes.Select(r => r.RouteID).Distinct())
     };                                     
  model.Routes = model.Routes.Add("All", "All", SelectListHelper.ListPosition.Random);
//or
  model.Routes = model.Routes.Add("All");
查看更多
够拽才男人
5楼-- · 2020-01-27 13:24

May not sound very elegant, but I usually do something like this:

    var items = repository.func.ToList();
    items.Insert(0, new funcItem { ID = 0, TextValue = "[None]" });
    ViewBag.MyData = new SelectList(items);
查看更多
Luminary・发光体
6楼-- · 2020-01-27 13:27

A work-around is to use @tvanfosson's answer (the selected answer) and use JQuery (or Javascript) to set the option's value to 0:

$(document).ready(function () {
        $('#DropDownListId option:first').val('0');
    });

Hope this helps.

查看更多
欢心
7楼-- · 2020-01-27 13:28

I don't if anybody else has a better option...

<% if (Model.VariableName == "" || Model.VariableName== null) { %>
   <%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"], "", 
        new{stlye=" "})%>
<% } else{ %>
<%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"], 
        Model.VariableName, new{stlye=" "})%>
<% }>
查看更多
登录 后发表回答