Pau*_*ann 5 c# html-helper asp.net-mvc-3
我正在使用表达式构建一个自定义HTML帮助器来绘制标签云,其中进入标签云的数据来自表达式.我会让代码在这里谈谈:
查看模型
public class ViewModel
{
public IList<MyType> MyTypes { get; set; }
public IList<MyOtherType> MyOtherTypes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
视图
<div>
@Html.TagCloudFor(m => m.MyTypes)
</div>
<div>
@Html.TagCloudFor(m => m.MyOtherTypes)
</div>
Run Code Online (Sandbox Code Playgroud)
帮手
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
}
Run Code Online (Sandbox Code Playgroud)
我已经快速浏览过并完成了常规的Google搜索,但我似乎无法找到具体的答案.我认为它在某个地区,expression.Compile().Invoke()但我不确定要通过的正确参数是什么.
我也应该提一下,MyType并且MyOtherType有一个类似的属性,Id但这里没有继承,它们是完全独立的对象因此我限制我的TPropertyas IList<MyType>和IList<MyOtherType>.我在这里走错了道路,我觉得这应该是显而易见的,但我的大脑不会玩.
以下应该这样做:
public static MvcHtmlString TagCloudFor<TModel , TProperty>( this HtmlHelper<TModel> helper , Expression<Func<TModel , TProperty>> expression )
where TProperty : IList<MyType>, IList<MyOtherType> {
//grab model from view
TModel model = (TModel)helper.ViewContext.ViewData.ModelMetadata.Model;
//invoke model property via expression
TProperty collection = expression.Compile().Invoke(model);
//iterate through collection after casting as IEnumerable to remove ambiguousity
foreach( var item in (System.Collections.IEnumerable)collection ) {
//do whatever you want
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3659 次 |
| 最近记录: |