This post explains how to create a controller rendering and related items like layout, templates, presentation details in Sitecore MVC with a simple example.
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
Name the controller as ‘Cart’ and create a new action method ‘List’ inside it as shown below.
CartController.cs
public class CartController : Controller
{
public ActionResult List()
{
CartList model = new CartList();
//model = ………..; Perform database operations and retrieve model details
return View(model); //return model details to the view
}
}
Create a corresponding view for this action method. i.e., create List.cshtml under Views/Cart/ path in the same .NET solution. Sample view file is shown below.
List.cshtml
@model Sitecore.MyMVCSolution.Website.Models.CartList
@{
if(Model!=null)
{
foreach(item in Model.CList)
{
<div class="testrow">
<div class="prod-name-css">@item.ProductName</div>
<div class="prod-qty-css">@item.ProductQty</div>
</div>
}
}
else
{
<div>
<h4 style="text-align:center;">
There are no items in this cart.
</h4>
</div>
}
}
Right click on Renderings, click on Insert->Controller Rendering. Enter the data values as shown below.
Controller: Cart, Controller Action: List
Save and publish the item.
Under Layouts, select the layout you want to choose.
Sample Layout File with placeholders (SampleLayout.cshtml):
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sample Page</title>
</head>
<body>
<div class="header">
@Html.Sitecore().Placeholder("phHeader")
</div>
<div class="Body">
@Html.Sitecore().Placeholder("phCartListController")
</div>
<div class="footer">
@Html.Sitecore().Placeholder("phFooter")
</div>
</body>
</html>
Under Controls, add the rendering items for this page. For each placeholder in the layout file add a presentation/rendering item. Here the rendering item could be ‘view rendering’, ‘controller rendering’, ‘XSLT rendering’ or of any other type based on our need.
Now run the URL ‘http://Website/Cart/List’ from the browser. This will hit the ‘List’ content item in the sitecore. While rendering the ‘List’ item, the controller action is called. The controller action will return a model to the view. The view is rendered and added to the placeholder ‘phCartListController’ in the layout file.