Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code a C# Extension method to turn a Domain Model object into an Interface object?

When you have a domain object that needs to display as an interface control, like a drop down list, ifwdev suggested creating an extension method to add a .ToSelectList().

The originating object is a List of objects that have properties identical to the .Text and .Value properties of the drop down list. Basically, it's a List of SelectList objects, just not of the same class name.

I imagine you could use reflection to turn the domain object into an interface object. Anyone have any suggestions for C# code that could do this? The SelectList is an MVC drop down list of SelectListItem.

The idea of course is to do something like this in the view:

<%= Html.DropDownList("City", 
         (IEnumerable<SelectListItem>) ViewData["Cities"].ToSelectList() )
like image 682
Zachary Scott Avatar asked Apr 06 '10 21:04

Zachary Scott


People also ask

What is AC code in programming?

A C program is a set of functions, data type definitions and variable declarations contained in a set of files. A C program always start its execution by the function with name main .

Is there AC coding language?

C (pronounced like the letter c) is a general-purpose computer programming language. It was created in the 1970s by Dennis Ritchie, and remains very widely used and influential. By design, C's features cleanly reflect the capabilities of the targeted CPUs.


2 Answers

It's easier to make the SelectList part of your ViewModel object.

Anyway, you just have to loop through the IEnumerable and add each item to a new SelectList object and 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 refactor these 2 similar methods into one?

like image 129
Robert Harvey Avatar answered Oct 09 '22 08:10

Robert Harvey


These are the two extension methods I use to create select 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

like image 29
Charlino Avatar answered Oct 09 '22 07:10

Charlino