This tutorial explains what a View rendering is and how to implement it in Sitecore MVC with an example.
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’
<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">
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.