Reputation: 42957
I have some doubts about how to work a @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 a model for the current view, so an object that is an instance of this class contains all the information that I have to show in this view. Is this interpretation correct or am I missing something?
Another doubt is: who populate this model? is it populated by the specific controller of the view?
Upvotes: 6
Views: 10735
Reputation: 32661
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 interpretation correct or am I missing something?
Yes, you have interpreted it correctly.
is it populated by the specific controller of the view?
Yes, it is populated by a specific action of the specific controller for that view.
Upvotes: 4
Reputation: 2673
In ASP.NET MVC, a controller can pass strongly-typed models to its view. This can be done with the following kind of code in your controller method:
public ActionResult Show()
{
MyModelClass model = new MyModelClass()
return View(model);
}
Then, in order to access your strongly-typed model in your view, you need to first define (in your view) the type of model it is expecting. This is done by including a @model
directive at the top of your view file:
@model Full.Namespace.MyModelClass
This allows the view to then access your models property in a strongly-typed manner, by using your model properties:
@Html.DisplayFor(model => model.MyProperty)
Upvotes: 4
Reputation: 28097
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
Upvotes: 6