Work with Favorite Lists

I got a model defined as IEnumerable<MyViewModel> , which I tried to use to create a select list ( Html.SelectListFor ). But I could not figure out how to do this. This made me take a look at the simple Html.SelectList method.

Since he wants an IEnumerable<SelectListITem> , and I don't want to add view logic to my controller or logic, I decided to create the following extension method:

 public static class ExtensionMethods { public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> items, Func<T, string> valueSelector, Func<T, string> textSelector) { return items.Select(item => new SelectListItem { Text = textSelector(item), Value = valueSelector(item) }).ToList(); } } 

What I use as:

 @Html.DropDownList("trainid", Model.ToSelectList(item => item.Id, item => item.Name)); 

This does not seem to be the best solution. How was I supposed to do?

+4
source share
3 answers

Guess the answer is that I'm already using the best solution.

+1
source

JG,

funnily enogh, I should have found a similar article when looking for such a solution. I have an extn method that goes:

 public static IList<SelectListItem> ToSelectItemList<T>( this IEnumerable<T> list, Func<T, string> textSelector, Func<T, string> valueSelector, T selected) where T : class { var results = new List<SelectListItem>(); if (list != null) { results.AddRange( list.Select(item => new SelectListItem { Text = textSelector.Invoke(item), Value = valueSelector.Invoke(item), Selected = selected != null ? selected.Equals(item) : false })); } return results; } 

and called as:

 <%: Html.DropDownList("Base.EntityRootID", Model.EntityRootList.ToSelectItemList(foo => foo.EntityName, foo => foo.ID.ToString(), Model.Base.EntityRoot))%> 

how strange. I really like this method, since it is both general and using the object itself to compare the selected element with means that you are not ar $ e around with comparison id, etc.

works for me.

0
source

I really like this approach. I made one change to add the selected item parameter.

 public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> items, Func<T, string> value, Func<T, string> text, object selectedValue) { return items.Select(item => new SelectListItem { Text = text(item), Value = value(item), Selected = (selectedValue.ToString() == value(item)) }); } 

In addition, I was able to use this code with Html.DropDownListFor, which completely eliminated the need for magic lines:

 Html.DropDownListFor(x => x.ContractId, Model.Contracts.ToSelectList(x => x.Value, x => x.Disp, Model.ContractId)) 
0
source

All Articles