chakmeshma
chakmeshma

Reputation: 284

What does @model exactly do?

Whenever I put @model [Type] on top of my Razor pages, some of the generic types and methods have their type parameters resolve to [Type], for example:

string DisplayNameFor<TResult>(Expression<Func<TModel, TResult>> expression);

becomes

string DisplayNameFor<TResult>(Expression<Func<[Type], TResult>> expression);

How does ASP.NET Core achieve that? How does the TModel type parameter becomes [Type]?

Upvotes: 4

Views: 3096

Answers (1)

Edward
Edward

Reputation: 29976

@model

The @model directive specifies the type of the model passed to a view:

@model TypeNameOfModel

In an ASP.NET Core MVC app created with individual user accounts, the Views/Account/Login.cshtml view contains the following model declaration:

@model LoginViewModel

The class generated inherits from RazorPage<dynamic>:

public class _Views_Account_Login_cshtml : RazorPage<LoginViewModel>

Razor exposes a Model property for accessing the model passed to the view:

<div>The Login Email: @Model.Email</div>

The @model directive specifies the type of this property. The directive specifies the T in RazorPage<T> that the generated class that the view derives from. If the @model directive isn't specified, the Model property is of type dynamic. The value of the model is passed from the controller to the view. For more information, see Strongly typed models and the @model keyword.

Reference: @model

Upvotes: 5

Related Questions