Automapper Mapping IEnumerable<SelectListItem> for Dropdown Menu

*爱你&永不变心* 提交于 2019-12-04 16:05:02

For the record, here is what I was talking about in the comments to Jakub's answer:

public static class EnumerableExtensions
{
    public static IEnumerable<SelectListItem> ToSelectList<T, TTextProperty, TValueProperty>(this IEnumerable<T> instance, Func<T, TTextProperty> text, Func<T, TValueProperty> value, Func<T, bool> selectedItem = null)
    {
        return instance.Select(t => new SelectListItem
        {
            Text = Convert.ToString(text(t)),
            Value = Convert.ToString(value(t)),
            Selected = selectedItem != null ? selectedItem(t) : false
        });
    }
}

Needless to say, this is dramatically simpler and accomplishes the same thing (and is actually more robust in the event that the property paths are non-simple, since Jakub's solution will not work with nested properties).

(This is not really an answer, I'm posting it as a community wiki just to help elaborate a point)

Controller is a perfect place to populate your view models.

You can remove plumbing code by using this extension method:

public static class EnumerableExtensions
{
    public static IEnumerable<SelectListItem> ToSelectList<T, TTextProperty, TValueProperty>(this IEnumerable<T> instance, Expression<Func<T, TTextProperty>> text, Expression<Func<T, TValueProperty>> value, Func<T, bool> selectedItem = null)
    {
        return instance.Select(t => new SelectListItem
        {
            Text = Convert.ToString(text.ToPropertyInfo().GetValue(t, null)),
            Value = Convert.ToString(value.ToPropertyInfo().GetValue(t, null)),
            Selected = selectedItem != null ? selectedItem(t) : false
        });
    }

    public static PropertyInfo ToPropertyInfo(this LambdaExpression expression)
    {
        MemberExpression body = expression.Body as MemberExpression;

        if (body != null)
        {
            PropertyInfo member = body.Member as PropertyInfo;
            if (member != null)
            {
                return member;
            }
        }

        throw new ArgumentException("Expression is not a Property");
    }
}

model.Roles = context.Roles.ToSelectList(r => r.RoleID, r => r.Description);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!