views:

1344

answers:

5
 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?

+2  A: 
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;
Matt Hinze
+5  A: 
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)
       });
Mehrdad Afshari
+4  A: 

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:

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.

public ActionResult DoSomething(int? customerId)
{
  if(customerId != null)
  {
    // do something with the value
  }
}
Steve Willcock
+1 just did this in a view; simple and it works :)
Dan
A: 

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.

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

Tony Borf
A: 

firt put your default value in the list

list.add(your default list item)

and then do list.addrange(linq select query)

cheers

Marko