Use MVC models

Last updated Wednesday, October 19, 2016 in Sitecore Experience Platform for Developer
Keywords: Development

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:

  1. Create a model class that implements all the model properties you need. If you use the Sitecore.Mvc.Presentation.IRenderingModel interface, the Initialize method is called on model creation.
  2. In the content tree, in the /sitecore/layout/Models folder, create a definition item for the model.
  3. In the Model Type field, specify the type of the model class, for example, Sitecore.Example.Employees,<your-assembly-name>.

    Picture 8

  4. Iterate through the child item properties of the model to generate the HTML markup in your view rendering cshtml file. For example:
    @model Sitecore.Example.Employees
    <table>
        @foreach (var empl in @Model)
        {
            <tr>
                <td>Employee name:</td><td style="color:orange">@empl.Name</td>
                <td>Years of work:</td><td style="color:orange">@empl.YearsOfWork</td>
            </tr>
        }
    </table>
  5. In the definiton item for the view rendering, in the Model field, enter the name of the model item that you have created.

    Picture 9

  6. Create an item template with the names of the fields that you expect to access in your .NET model. For example, Name and YearsOfWork.

    Picture 10

  7. In the /sitecore/content root item, create a parent item for the model with any template, and under this parent item, create several model items with relevant field values:

    Picture 7

  8. 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.