An extension method to create a SelectList, make your code neat & clean in MVC

When you have an IEnumerable model list bind to a select list items, you always need to write

var Items = Service.FindAll().Select(p => new SelectListItem() { Text = p.Name, Value = p.Id });

Here I create a extension method of IEnumerable<T> called “ToSelectList”,

    public static class SelectListExtensions
        public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> items,
            Func<T,string> text, Func<T,string> value = null, Func<T,Boolean> selected = null)
            return items.Select(p => new SelectListItem
                Text = text.Invoke(p),
                Value = (value==null? text.Invoke(p): value.Invoke(p)),
                Selected = selected == null? false: selected.Invoke(p)

When you read the list from database and bind to a select list, you can write this way,

var Items = Service.FindAll().ToSelectList(p=>p.Name, p=>p.Id);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s