See MajoBs answer.
Although if you're using the @Html.DropDownListFor()
Helper, you could also specify the Id 0 row using the optionLabelArgument:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
string optionLabel
)
Update:
I think the reason MajoB's example doesn't work is because you are using an anonymous type in the Linq query, but define a string in the .Insert()
statement.
I believe it is not possible to reuse the same anonymous type that was used in the LINQ query in the .Insert()
statement.
So you would have to use a regular type.
(from x in
(from li in dContext.states
where li.state >= 0
select new {
value = li.state,
text = li.something
}).AsEnumerable()
select new SelectListeItem {
Value = x.value.ToString()
Text = x.text
}).ToList().Insert(0, new SelectListItem() { .. });
The nested query is necessary because the .ToString()
can't be translated to sql. The .AsEnumerable()
call created an in-memory list where .ToString
will work on.
I am actually using a Extension method like this in our code base.
But it requires LinqKit to work.
public static IList<SelectListItem> ToSelectList<T>(this IQueryable<T> query
, Expression<Func<T, long>> value
, Expression<Func<T, string>> text
, string nullText = null)
{
var result = (from x in
(from y in query.AsExpandable()
select new
{
Value = value.Invoke(y),
Text = text.Invoke(y),
}).AsEnumerable()
select new SelectListItem
{
Value = x.Value.ToString(),
Text = x.Text.ToString()
}).ToList();
AddNullText(nullText, result);
return result;
}
private static void AddNullText(string nullText, List<SelectListItem> result)
{
if (nullText != null)
{
result.Insert(0, new SelectListItem()
{
Value = "",
Text = nullText,
});
}
}
(+ the same Extension method with Expression<Func<T, string>>
, etc.. as second parameter.)