Use MVC models

Abstract

An MVC model is designed for passing structured data to an MVC view.

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

    E8867E720E944D12B54606B8DBFE1482.png
  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.

    8265090C17C241B99704840665F1CD6A.png
  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.

    C22BDEABE83E4B9F8D51B45F6BA7FF05.png
  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:

    9E9B74984E8F489F9C0FA24433C64553.png
  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.