How to code a C # extension method to turn a domain model object into an interface object?

When you have a domain object that should be displayed as an interface control, such as a drop-down list, ifwdev suggested creating an extension method to add. ToSelectList ().

The source object is a list of objects that have properties identical to the .Text and .Value properties of the drop-down list. Basically, this is a list of SelectList objects, just not the same class name.

I assume that you can use reflection to turn a domain object into an interface object. Anyone have suggestions for C # code that can do this? SelectList is a MVC SelectListItem drop-down list.

The idea is to do something like this in a view:

<%= Html.DropDownList("City", 
         (IEnumerable<SelectListItem>) ViewData["Cities"].ToSelectList() )
+5
source share
2 answers

It’s easier to make SelectListpart of your object ViewModel.

In any case, you just need to go through IEnumerableand add each element to the new object SelectListand return it.

public static List<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, string> text, Func<T, string> value, string defaultOption) 
{ 
    var items = enumerable.Select(f => new SelectListItem() { Text = text(f), Value = value(f) }).ToList(); 
    items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" }); 
    return items; 
} 

How to reorganize these two similar methods into one?

+4
source

These are two extension methods that I use to create favorites lists.

public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> collection, Func<T, string> text, Func<T, string> value)
{
    return collection.ToSelectList(text, value, x => false);
}

public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> collection, Func<T, string> text, Func<T, string> value, Func<T, bool> selected)
{
    return (from item in collection
            select new SelectListItem()
                       {
                           Text = text(item),
                           Value = value(item),
                           Selected = selected(item)
                       });
}

HTHS,
Charles

+4
source

All Articles