Is IEnumerable special in razor?

2019-06-09 06:30发布

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条回答
乱世女痞
2楼-- · 2019-06-09 07:15

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!

查看更多
登录 后发表回答