简体   繁体   中英

How can I return an object of type EntityCollection for use with a SelectList in ASP.NET MVC?

I have made an extension to DropDownList in the ASP.NET MVC HtmlHelper to make it render optgroup 's. It works 'fine' when the second collection is an IList , but I quickly found out that if it's not, or in my case if it's an EntityCollection it crashes because the SelectList is unable to enumerate it.

So, I'm here asking for help from anyone who knows how I can bypass the issue. I thought about passing in a Type of what the second collection is and then performing casts internally, but that just doesn't feel right...

Anyway, I hope someone can help me, here's the current code:

internal IList<GroupListItem> GetListItems() {
    return (from object Item in Items
            select new GroupListItem {
                Children = new SelectList((Eval(Item, this.ChildrenField) as IEnumerable), this.ChildDataValueField, this.ChildDataTextField, this.ChildSelectedValue),
                Label = (Eval(Item, this.LabelField) as string)
            }).ToList();
}

private static object Eval(
    object Container,
    string Expression) {
    object Value = Container;

    if (!String.IsNullOrEmpty(Expression)) {
        Value = DataBinder.Eval(Container, Expression);
    };

    if (Value is IList) {
        return Value;
    };

    return Convert.ToString(Value, CultureInfo.CurrentCulture);
}

您是否考虑过使用IEnumerable代替IList?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM