调用 DisplayNameFor 的 IEnumerable 重载 [英] Calling IEnumerable overload of DisplayNameFor
问题描述
这适用于抓取标题(NOT VALUES):
This works for grabbing the headers(NOT VALUES):
@model IEnumerable<SomeModel>
...
<th>@Html.DisplayNameFor(m => m.SomeModelProperty)</th>
如果 SomeModelProperty 是:
Which if SomeModelProperty were:
[Display(Name = "An Excellent Header")]
SomeModelProperty { get; set; }
然后它会在标题 th
元素中显示一个优秀的标题".
Then it would display "An Excellent Header" in the header th
element.
您会认为这不起作用,因为模型是 IEnumerable,它没有 m.SomeModelProperty,但它起作用是因为 HtmlHelper 有一个 HtmlHelper
这样的lambda 的参数是 TModel
,而不是 IEnumerable
.由于这仅使用元数据,因此不需要集合中的项目.(尽管 m.
上的智能感知会骗你,让你认为它是一个集合).我不确定这个很酷的重载是什么时候添加的,但对于 Index.cshtml 来说非常方便,并且消除了诸如 @Html.DisplayNameFor(m => @Model.FirstOrDefault().SomeModelProperty)之类的时髦东西代码>我想避免.
You would think this wouldn't work because the model is IEnumerable, which wouldn't have a m.SomeModelProperty, but it works because HtmlHelper has a HtmlHelper<IEnumerable<TModel>>
such that the parameter of the lambda is TModel
, not IEnumerable<TModel>
. Since this just uses metadata, there is no need for an item from the collection. (Although intellisense on m.
will lie to you and make you think it's a collection). I'm not sure when this cool overload was added, but is quite handy for Index.cshtml and does away with funky things like @Html.DisplayNameFor(m => @Model.FirstOrDefault().SomeModelProperty)
which I want to avoid.
http://msdn.microsoft.com/en-us/library/hh833697(v=vs.108).aspx
但是,当我的模型不是 IEnumerable 而是包含 IEnumerable 作为属性时,我无法弄清楚如何使其工作,例如:
However, I can't figure out how to get this to work when my model is not IEnumerable, but instead contains IEnumerable as a property, such as:
public class SomeList
{
public List<SomeModel> SomeModels { get; set; }
public int Page { get; set; }
public DateTime CurrentAsOf { get; set; }
}
我希望对泛型类型参数进行明确,但我认为类型参数是由从页面创建的 HtmlHelper 滴下的引擎指定的.我可以在页面中声明一个新的 HtmlHelper,或者以某种方式明确指定类型参数吗?
I was hoping to be explicit with the generic type parameters, but I think the type parameters are specified by the engine that trickles down from the HtmlHelper created with the page. Can I declare a new HtmlHelper in the page, or somehow specify the type parameters explicitly?
Index.cshtml:
Index.cshtml:
@model SomeList
//No idea how to do this:
@Html.DisplayNameFor<IEnumerable<SomeModel>>(m => m.SomeModelProperty)
推荐答案
另一种类似的解决方法即使没有行也能起作用:
Another similar workaround that works even if there are no rows could be:
...
@{var dummy = Model.FirstOrDefault(); }
<tr>
<th>
@Html.DisplayNameFor(model => dummy.SomeModelProperty)
</th>
...
这篇关于调用 DisplayNameFor 的 IEnumerable 重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!