Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a default SelectListItem

 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?

like image 245
Danny Avatar asked May 21 '09 17:05

Danny


People also ask

How do I add an item to SelectListItem?

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

What is SelectListItem MVC?

SelectListItem is a class which represents the selected item in an instance of the System. Web. Mvc.

What is IEnumerable SelectListItem?

SelectList(IEnumerable) Initializes a new instance of the SelectList class by using the specified items for the list. SelectList(IEnumerable, Object) Initializes a new instance of the SelectList class by using the specified items for the list and a selected value. SelectList(IEnumerable, Object, IEnumerable)


2 Answers

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)
       });
like image 167
mmx Avatar answered Sep 19 '22 03:09

mmx


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
  }
}
like image 30
Steve Willcock Avatar answered Sep 19 '22 03:09

Steve Willcock