You use MVC models to pass structured data to MVC views, where this data is used to render HTML markup using Razor syntax. Sitecore view renderings use an MVC view for rendering the output markup, so you can set an appropriate model item for these renderings to pass data from content items.
To use an MVC model with a view rendering:
- Create a model class that implements all the model properties you need. If you use the
Initializemethod is called on model creation
- In the content tree, in the
/sitecore/layout/Modelsfolder, create a definition item for the model.
- In the Model Type field, specify the type of the model class, for example,
- Iterate through the child item properties of the model to generate the HTML markup in your view rendering
cshtmlfile. For example:
@foreach (var empl in @Model)
<td>Employee name:</td><td style="color:orange">@empl.Name</td>
<td>Years of work:</td><td style="color:orange">@empl.YearsOfWork</td>
- In the definiton item for the view rendering, in the Model field, enter the name of the model item that you have created.
- Create an item template with the names of the fields that you expect to access in your .NET model. For example,
- In the
/sitecore/contentroot item, create a parent item for the model with any template, and under this parent item, create several model items with relevant field values:
- In the layout definition of the content item, set the parent item of the model as the data source for the view rendering.
When you navigate to an item and this item uses a view rendering that has a model set, the
Initialize model method reads information from the items under the parent item (data source) of the model. This requires that the model inherits from the
IRenderingModel interface. The view rendering can generate output markup according to the model data.