Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]?

like image 239
chakmeshma Avatar asked Oct 22 '25 03:10

chakmeshma


1 Answers

@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

like image 133
Edward Avatar answered Oct 23 '25 17:10

Edward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!