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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With