【发布时间】:2012-08-23 21:23:26
【问题描述】:
我正在构建一个带有表达式的自定义 HTML 帮助程序来绘制标签云,其中进入标签云的数据来自表达式。我会让代码在这里说话:
查看模型
public class ViewModel
{
public IList<MyType> MyTypes { get; set; }
public IList<MyOtherType> MyOtherTypes { get; set; }
}
查看
<div>
@Html.TagCloudFor(m => m.MyTypes)
</div>
<div>
@Html.TagCloudFor(m => m.MyOtherTypes)
</div>
助手
public static MvcHtmlString TagCloudFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) where TProperty : IList<MyType> where TProperty : IList<MyOtherType>
{
// So my actual question here is: how do I get my IList<TProperty> collection
// so I can iterate through and build my HTML control
}
我快速浏览了一下周围并进行了通常的 Google 搜索,但我似乎无法找到具体的答案。我假设它在expression.Compile().Invoke() 区域的某个地方,但我不确定要传递的正确参数是什么。
我还应该提到MyType 和MyOtherType 具有Id 的相似属性,但这里没有继承,它们是完全独立的对象,因此我将TProperty 限制为IList<MyType> 和@987654330 @。我是不是走错了路,我感觉这应该是显而易见的,但我的大脑没有在玩。
【问题讨论】:
-
如果你必须约束,一个 TProperty: IList
和一个 TProperty: IList 和 MyType 和 MyOtherType 不兼容的地方,比它不起作用。两个约束都适用。 -
@Maarten:是的,我也这么认为,我现在已经删除了第二个约束以使列表正常工作,然后将重新查看我的继承结构。这些对象是 Entity Framework 的 POCO 实体,所以看起来我需要一个共同的祖先。
标签: c# asp.net-mvc-3 html-helper