Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the @model keyword do in an ASP.NET MVC View?

Tags:

c#

.net

asp.net

I have some doubts about how work @model statement into a cshtml view. In my code, I have something like this:

@model MyCorp.EarlyWarnings.WebInterface.Models.HomePageModel

So what exactly does this do?

I think that I am including this HomePageModel as model for the current view so an object that is instance of this class contains all the information that I have to show in this view, is it interpretration correct or am I missing something?

Another doubt is: who populate this model? is it populated by the specific controller of the view?

like image 917
AndreaNobili Avatar asked Dec 15 '22 00:12

AndreaNobili


2 Answers

The thing you have to remember is that the Razor View engine compiles your CSHTML pages into normal C# classes.

So when you define

@model Something

Razor actually produces something along the lines of

public class _Path_To_View_cshtml : WebViewPage<Something>
{
    // mcguffins to make everything happen
}

Then within that class everything is "inverted" from your CSHTML page. So when you write

<div>@Model.Foo</div>

in your CSHTML, this will be translated to something like

WriteLiteral("<div>");
Write(Model.Foo);
WriteLiteral("</div>");

In terms of the second part of your question about where Views are called from, any Controller Action can call a View (in the same application at least) by supplying the path to the view in the result:

return this.View("~/path/to/view", someModel);

The default is that if you return

return this.View(someModel);

the path used will be ~Views/ControllerName/ActionName.cshtml

like image 111
dav_i Avatar answered Jan 04 '23 22:01

dav_i


I think that I am including this HomePageModel as model for the current view so an object that is instance of this class contains all the information that I have to show in this view, is it interpretration correct or am I missing something?

Yes, you have interpretted it correctlty.

is it populated by the specific controller of the view?

Yes, it is populated by specific action of the specific controller for that view.

like image 40
Ehsan Avatar answered Jan 05 '23 00:01

Ehsan