Im trying to create an dropdownlist from an IList with following syntax:
@Html.DropDowntListFor(Model.VisitingAddresses, vistingAddress => vistingAddress.Id, vistingAddress => vistingAddress.Name)
This works with the following code:
public static IHtmlString DropDowntListFor
<TModel>(this HtmlHelper htmlHelper, IList<TModel> list, Expression<Func<TModel, string>> value, Expression<Func<TModel, string>> text)
{
var dropdownName = value.Parameters.First().Name;
var selectedListItem = new List<SelectListItem>();
var values = list.AsQueryable().Select(value).ToList();
var texts = list.AsQueryable().Select(text).ToList();
int i;
for (i = 0; i < values.Count; i++)
{
selectedListItem.Add(new SelectListItem
{
Value = values[i],
Text = texts[i]
});
}
return htmlHelper.DropDownList(dropdownName, selectedListItem);
}
But as you can see the code above (in the htmlhelper) is really really ugly, is there someone that knows an more beautiful way (in code) for in the html helper?
Thanks in advance.
Are you after something like this?
Note that if you don’t need the text selector as an expression tree, you can simplify it slightly further: