Views use a class called a WebViewPage. That's what a view is. The reason you have access to an object called Model
is because of this (notice that it's a property of the class). You can access the model at any time in a Razor view with @Model
.
@Html
is the way we access Html helpers (HtmlHelper) from our Razor view; useful for generating some HTML for us. DisplayNameFor()
is one of many extension methods.
That long, scary parameter that it wants is actually relatively simple. Basically it wants you to give it an anonymous function. This technique is called a Lambda Expression. In C# (for comparison) it might look like this:
SomeMethod(x => x.SomeProperty);
It's basically a short-hand way of creating a function on the spot (typically on one line) and doing something with the property. In the case of the Html
object, it's methods typically expect a lambda expression involving the model.
Why do it this way?
Because it gives you a tremendous amount of power. By using a function you can do anything inside it and anything involving the object (the parameter).
For example:
@Html.LabelFor(Function(f) f.Projects.SingleOrDefault(Function(g) g.Id = 5))
What's this do?
- I access the view's HtmlHelper object with
@Html
. - I'm using the method
LabelFor
to generate a<label for="">
tag. - I begin my lambda expression and give my parameter a name. It can be any name I want and the helper will automatically give me the model (it's designed to do that). In this case I named it
f
. - Now that I have my object
f
I need to select which object I'm generating a label for. In this example let's pretend my model isn't aProject
but instead it is a different object which contains an array/list of projects. - I select the list of projects (
f.Projects
) and then I want to select a single project. I do this withSingleOrDefault()
. SingleOrDefault takes another lambda and this time it knows to pass in the list of projects as the parameter. I'll call this list of projectsg
. - Now with the list of projects I will finally select which object.
The final statement, transferred to English means:
Given a list of projects from the Model, called "f", take them all and select a single project, called "g", where the Id of the project is equal to 5 and generate an HTML label.