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?
SelectList list = new SelectList(repository. func. ToList()); ListItem li = new ListItem(value, value); list. items.
SelectListItem is a class which represents the selected item in an instance of the System. Web. Mvc.
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)
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)
});
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With