Mani
Mani

Reputation: 23

DisplayFor method requires at least 2 parameters as per MSDN, but it seems to work with 1 parameter only

While learning ASP.Net MVC from tutorial on MSDN, I see DisplayFor method being used as: @Html.DisplayFor(x => x.SomeProperty)

or as: @Html.DisplayFor(modelItem => item.Releasedate)

But documentation seems to specify at least 2 parameters (here).

One more issue: since modelItem parameter is never used on right-side of =>, I tried replacing modelItem with () but get red squiggly line that says "Type args for method cannot be inferred from usage...":

@Html.DisplayFor(()=> item.Releasedate)

My main concern is that documentation shows DisplayFor method needs at least 2 parameters, but wherever I saw it in tutorials they only had 1 parameter and that was a lambda expression!

Upvotes: 0

Views: 787

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039060

The DisplayFor is an extension method of the HtmlHelper class. This means that the first argument that you see in MSDN documentation is the HtmlHelper class and there are two ways to call this extension method.

Either on an instance of the HtmlHelper class in which case you can omit the first argument (preferred approach):

 @Html.DisplayFor(x => x.SomeProperty)

Or as a plain static method:

 @DisplayExtensions.DisplayFor(Html, x => x.SomeProperty)

Basically extension methods allow you to add methods on existing classes without the need to modify the code of those classes and then use those new methods as if they were first class citizens.

Upvotes: 1

Related Questions