Is IEnumerable special in razor?

醉酒当歌 提交于 2019-12-23 05:42:19

问题


In an ASP.NET MVC razor View detail page I can have a model like:

@model MyClass

And then do something like:

@html.DisplayNameFor(m => m.MyProperty)

But in a list page, where I have:

@model IEnumerable<MyClass>

The same @html code works. I wouldn't expect it to, because MyProperty isn't a property of IEnumerable. Is IEnumerable "special" in that the razor view engine knows to look at the properties of the type parameter MyClass, rather than the properties of IEnumerable itself?


回答1:


It's not much that IEnumerable is special. If you were to use @html.DisplayFor(m => m.MyProperty) you would get an error that your IEnumerable list doesn't contain a definition for "MyProperty". You would have to use a linq query to select one MyClass object or do a ForEach() over your model.

@html.DisplayNameFor IS special in that it has an overload for IEnumerable models. It knows you're really just after the display name for the property and since you have a strongly typed list it knows how to find the display name. It's a convenient feature!



来源:https://stackoverflow.com/questions/14391966/is-ienumerable-special-in-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!