asp.net-mvc 添加默认的 SelectListItem

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/894130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:35:38  来源:igfitidea点击:

Adding a default SelectListItem

asp.net-mvclinq

提问by Danny

 public IEnumerable<SelectListItem> GetList(int? ID)
 {
      return from s in db.List
             orderby s.Descript
             select new SelectListItem
             {
                 Text = s.Descript,
                 Value = s.ID.ToString(),
                 Selected = (s.ID == ID)
             };
 }

I return the above to a view and populate a DropDownList. I would like to add a default SelectListItem (0, "Please Select..")to the above linq result before it is returned to the view. Is this possible?

我将上述内容返回到视图并填充DropDownList. 我想SelectListItem (0, "Please Select..")在返回到视图之前为上面的 linq 结果添加一个默认值。这可能吗?

回答by Mehrdad Afshari

return new[] { new SelectListItem { Text = ... } }.Concat(
       from s in db.List
       orderby s.Descript
       select new SelectListItem
       {
           Text = s.Descript,
           Value = s.ID.ToString(),
           Selected = (s.ID == ID)
       });

回答by Steve Willcock

As you are using ASP.NET MVC, you can do this in the view by specifying a value for the optionLabel parameter of the DropDownField method of the HtmlHelper - e.g:

当您使用 ASP.NET MVC 时,您可以在视图中通过为 HtmlHelper 的 DropDownField 方法的 optionLabel 参数指定一个值来执行此操作 - 例如:

htmlHelper.DropDownList("customerId", selectList, "Select One");

Putting this type of code in your UI layer is probably more appropriate than having it in the data layer. One downside to doing this is that your select box will have an empty string value, not a "0" for the 'Select One' option, but that is not really a problem as you can treat this as a null value if your controller action method can accept a nullable int for the relevant parameter - e.g.

将这种类型的代码放在您的 UI 层中可能比将其放在数据层中更合适。这样做的一个缺点是您的选择框将有一个空字符串值,而不是“选择一个”选项的“0”,但这并不是真正的问题,因为如果您的控制器操作,您可以将其视为空值方法可以接受相关参数的可为空的 int - 例如

public ActionResult DoSomething(int? customerId)
{
  if(customerId != null)
  {
    // do something with the value
  }
}

回答by Matt Hinze

var list = from s in db.List
           orderby s.Descript
           select new SelectListItem
           {
               Text = s.Descript,
               Value = s.ID.ToString(),
               Selected = (s.ID == ID)
           };

list.Insert(0, new SelectListItem { Text = "Please Select...", Value = string.Empty });
return list;

回答by Tony Borf

Here is what I did, I read my values from an XML file into an IList. I then inserted a new record into the IList at position 0. Then make a select list from the IList.

这就是我所做的,我将 XML 文件中的值读入 IList。然后我将一条新记录插入到 IList 的位置 0。然后从 IList 中创建一个选择列表。

IList< MY_DATA > mydata = (from tmp in myXML.Descendants("R").ToList()

                      select new MY_DATA
                      {
                         NR = tmp.Attribute("NR").Value,
                         NA = tmp.Attribute("NA").Value 
                      }).ToList<MY_DATA>();

mydata.Insert(0, new My_DATA() { NR = "", NA = "--Click to Select--" });

SelectList mylist = new SelectList(mydata, "NR", "NA");

IList< MY_DATA > mydata = (来自 myXML.Descendants("R").ToList() 中的 tmp

                      select new MY_DATA
                      {
                         NR = tmp.Attribute("NR").Value,
                         NA = tmp.Attribute("NA").Value 
                      }).ToList<MY_DATA>();

mydata.Insert(0, new My_DATA() { NR = "", NA = "--点击选择--" });

SelectList mylist = new SelectList(mydata, "NR", "NA");

回答by Marko

firt put your default value in the list

首先把你的默认值放在列表中

list.add(your default list item)

list.add(您的默认列表项)

and then do list.addrange(linq select query)

然后做 list.addrange(linq select query)

cheers

干杯

回答by Rasha

After I reviewed many questions, and I don't find what i'm looking for.I don't need many lines of code to just have a simple drowpdown. so I want to share with you what I use and it easy and simple.. ( specially if you don't want to use and Entity Framework..

在我查看了很多问题之后,我没有找到我要找的东西。我不需要很多代码行来做一个简单的下拉列表。所以我想和你分享我使用的东西,它简单易行..(特别是如果你不想使用和实体框架..

using System.Web.Mvc;

使用 System.Web.Mvc;

SelectList(IEnumerable items, string dataValueField, string dataTextField);

For Example:

例如:

in Controlleradd :

控制器中添加:

SelectList slTitle = new SelectList(Query.SelectAllTitle(), "TitleID", "TitleName");
ViewBag.TitleSelectList = slTitle; 

in Viewadd :

视图中添加:

@Html.DropDownList("TitleSelectList", "--please select--")

回答by Danniel Little

This is just for people who are using Webpages framwork (not MVC and webform) with Razor V2 and C#, you need do

这仅适用于在 Razor V2 和 C# 中使用网页框架(不是 MVC 和 webform)的人,您需要这样做

    @Html.DropDownList("category", "Please select", listData)

Note: OptionalLabel need to be the middle parameter.

注意:OptionalLabel 需要是中间参数。

Equivalent would be add a SelectListitem to your list data:

相当于将 SelectListitem 添加到您的列表数据:

    var list=db.Query("select id, name from dbtable");
    List<SelectListItem> listData = new List<SelectListItem>();
    listData.Add(new SelectListItem
    {
        Text = "Please select",
        Value = "",
    }); 

    foreach(var item in list)   {
        listData.Add(new SelectListItem  {
            Text = item.Name,
            Value = item.id,
            Selected = isSelected 
        });
    }

    @Html.DropDownList("play" , listData)