View rendering in Sitecore with example

Pranay
Mar 26, 2019  ·  32179 views

This tutorial explains what a View rendering is and how to implement it in Sitecore MVC with an example.

Renderings in Sitecore

If you are a beginner in Sitecore, then understanding what Renderings are in Sitecore is important. Here is a post on what renderings in Sitecore - What are renderings in Sitecore - a beginner guide

What is View Rendering in Sitecore mvc?

Renderings are used to render a page or a part of a page in Sitecore. There are many renderings in sitecore and one among them is the view rendering. View rendering is used in components which involve little logic without any database transaction or a MVC controller. It is used to render a .cshtml view file without any action controller.

Though there is no controller action involved, a model can be used with this view rendering. Here is a good example on the same.

When to use View rendering in Sitecore MVC ?

If you don’t need a controller action and if just a razor view is sufficient to implement your logic then you can use this rendering. Here is a detailed post on when to use which rendering in Sitecore

How to implement view rendering mvc?

1. Create a view model

Create a model class in your .NET solution or inside the Website folder of your sitecore instance. This class will be referred in Sitecore using the assembly name and class name, hence it should be available in website folder.(Compile and place the class DLL inside the Sitecore website bin folder).

2. Create a .cshtml file with name - ‘MyviewRendering.cshtml’

@model Sitecore.MyProjSolution.Website.Models.MyModel
<div class="container">
    <div class="row productList">
       <ul class=" list-inline pull-right">
            @foreach (var product in @Model.Products)
            {          
                <li> <a href="@product.URL" title ="@product.Name" rel="nofollow" target="_blank">
                </a></li>   
            }  
      </ul> 
    </div>
</div>

3. Create a view rendering in Sitecore MVC

Go to Layouts->Renderings, right click on Renderings and select Insert->View Rendering. Give some name as MyviewRendering and with below mentioned field values.

  • Path: Path to the razor view file i.e., “/Views/Shared/MyviewRendering.cshtml“.
  • Model: Click on insert link and select the sitecore Model we have created ‘MySitecoreModel’.
  • PlaceHolder: This is the placeholder in the Layout file where this view rendering should be rendered.
AUTHOR

Pranay

A Software Engineer by profession, a part time blogger and an enthusiast programmer. You can find more about me here.


Post a comment




Thank you! You are now subscribed.

Sign up for our newsletter

Subscribe to receive updates on our latest posts.

Thank you! You are now subscribed.