I’m fairly new at C# and MVC and have used lambdas on certain occasions, such as for anonymous methods and on LINQ.
Usually I see lambda expressions that look someth
I also struggled a lot to understand the codes generated by Visual Studio. Instead of providing a general explanation about lambda expression, I would like to put a context using ASP.NET MVC framework.
Suppose we prepared a Model class (e.g. Destination) with 2 attributes: City and ProvinceCode.
public class Destination
{
public string City { get; set; }
public string ProvinceCode { get; set; }
}
After generating the Controller and View, we should get the generated codes by Visual Studio as mentioned. Yet, the generated codes are somewhat hard to understand, especially for the data rows
@Html.DisplayFor(modelItem => item.City)
I just guess that the MVC team should think that Html helper class should be consistently used in the cshtml file. Thus, they tried to use tricks to pass the C# compiler. In this case, modelItem is not even used as an input parameter of this lambda expression. We can't use () as the type is NOT correct. That is why, if we replace model or any model object, the lambda expression works.
To be honest, I would like to rewrite the generated codes in a more readable form. Instead of using the Html helper class, we can simply render the correct output as follows:
@foreach (var item in Model) {
@* Code Generated by Visual Studio. modelItem is a dummy param *@
@Html.DisplayFor(modelItem => item.City)
@* A better way - simply get rid of Html helper class *@
@item.ProvinceCode
}