public static MvcHtmlString CheckBoxListFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var parameterName = ((MemberExpression)expression.Body).Member.Name;
var values = expression.Compile().Invoke(html.ViewData.Model);
if (typeof (TValue) == typeof (List<SelectListItem>))
{
foreach (var value in values)
{
but I get tvalue is not enumerable?? WHy?
}
}
我做错了什么?我想获得所有元素的列表?
答案 0 :(得分:3)
对象必须实现System.Collections.IEnumerable
或System.Collections.Generic.IEnumerable<T>
才能使用in a foreach loop(感谢评论@dcastro)
你在代码中检查它,但你不能保证它,这意味着你得到编译器错误。
我不得不承认我并不完全确定你要对expression.Compile()
做什么,但是我会在你完成循环之前尝试将它投射出来。
var values = expression.Compile().Invoke(html.ViewData.Model);
if (typeof (TValue) == typeof (List<SelectListItem>))
{
var listValues = (List<SelectListItem>)values;
foreach (var value in listValues )
{
// do something
}
}
答案 1 :(得分:2)
尝试添加where constraint,
public static MvcHtmlString CheckBoxListFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
where TValue : IEnumerable
{
}