Zac*_*ott 5 asp.net-mvc domain-driven-design selectlist selectlistitem
当您有一个需要显示为接口控件的域对象时,如下拉列表,ifwdev建议创建一个扩展方法来添加.ToSelectList().
原始对象是具有与下拉列表的.Text和.Value属性相同的属性的对象列表.基本上,它是SelectList对象的List,而不是同一个类名.
我想你可以使用反射将域对象转换为接口对象.任何人对C#代码都有任何建议吗?SelectList是SelectListItem的MVC下拉列表.
当然,想法是在视图中做这样的事情:
<%= Html.DropDownList("City",
(IEnumerable<SelectListItem>) ViewData["Cities"].ToSelectList() )
Run Code Online (Sandbox Code Playgroud)
制作物体SelectList的一部分更容易ViewModel。
无论如何,您只需循环遍历IEnumerable并将每个项目添加到一个新SelectList对象并返回它。
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;
}
Run Code Online (Sandbox Code Playgroud)