Enterprise Collaboration, Social Media and Custom Development

Ariesnet Blog

(888) 932-3375

info@ariesnet.com

When I first started working with Sitecore, much as the many samples of code I’ve seen, I was tempted to put a lot of data access and business logic in the code-behind of the aspx pages that comprise the Sitecore Layouts and the ascx controls that comprise the Sitecore Sublayouts.
But as the project grew, and I learned more about Sitecore, I felt discouraged at such a messy programming model. Particularly in controls that required lots of complicated logic, such as custom lists with custom pagination, as with search results or news article lists (once you go beyond FieldRenderers, things can get complex.)
To the junior developer this may seem like the normal way of doing things, but old-salts have experienced a better world and have learned (the hard way in many cases) the benefits of clean separation of concerns. Ideally, a programmer would keep the presentation logic separated from the data access and business logic. Code is cleaner and easier to maintain, and changes can be made more easily without impacting other layers. Not only does this technique tend to cause less bugs, but it also allows the bugs that do occur me more easily tracked and found early in the unit testing process – as it allows each individual unit of code to be tested separately.
So when it all comes together it all just works, as if by magic. But it isn’t magic. It’s the good, time-honored, tried and true, object-oriented principle of Separation of Concerns.
And so, with principle firmly in mind, I decided to find a better way to go about writing Sitecore code-behind.
Model-View-Controller sprang immediately to mind – my background in desktop application programming models served me well – but the MVC model doesn’t port well to the traditional ASP.Net Framework upon which Sitecore is based. Until Sitecore comes up with a version of itself that works on the recently released ASP.Net MVC Framework (which I would personally welcome and applaud) I would have to find another alternative.
Fortunately, one does exist. It’s the next best thing. It’s called the Model-View-Presenter pattern.



Sitecore actually lends itself beautifully to the MVP pattern. The biggest problem with MVP is the extra amount of work required to make it work. The basic principle is the separation of Model (data), View (presentation) and Presenter (the business object that attaches the data from the Model to objects in the View.) In the MVP pattern, an interface is created for each View object. Let’s take a look at the View.
The View represents, in essence, a page, a control – an object that will render visually on the browser. The interface for the View represents all the fields that need data within that View so it can be rendered.
The Presenter object will know how to attach data to that View. Which field from the Model to attach to which field in the View – and which transformations need to occur for the View object to have what it needs.
Then, the actual page or control (aspx or ascx code) just needs to know how to render that View object – it doesn’t need to know where the data comes from or what manipulations the data had to go through to match that View field. It just needs to know that it is rendering a list of News article objects and that a News article object will have a Title, a Date and a Summary. And it can then choose to use a Repeater control to render a template that will paint those three fields on the page, regardless of how that data got to it. Did the News article come from the News table or an RSS feed? It doesn’t care. The Presenter takes care of the details. The aspx or ascx control now just has to worry about how to render that View object. The code-behind becomes thin and easy to maintain.

So what’s the catch?

Typically, in a regular ASP.Net business application, a form has events that fire from buttons, dropdown lists and other controls. The View becomes convoluted and a lot of maintenance has to be performed on these View objects and lots of events have to be mapped and passed to the Presenter object.

This is usually more than the average developer wants to handle and it can create long development processes – turning the project expensive.

But the typical Sitecore website is more presentational than it is functional. This means there are a lot of repeated patterns from page to page and those patterns tend to be “read-only” in nature – not much “eventing” going back and forth.

This makes the MVP model very well suited for a Sitecore project. With a fistful of View objects you can satisfy most of the project’s needs, as these tend to be very reusable.

Here are some of the Views I’ve found tend to repeat themselves the most in a typical Sitecore website:

ViewFieldsExample CodeExample Usage
SimpleLinkUrl and Label<a href="<%# Eval("Url") %>"><%# Eval("Label") %></a>Menu, Navigation Panel, list of links
TitledLinkUrl, Label and Title<label><%# Eval("Title") %></label><a href="<%# Eval("Url") %>"><%# Eval("Label") %></a>News, Events, Press Releases
ImageLabelLinkUrl, Label, ImagePath, ImageAlt<a href="<%# Eval("Url") %>"><img src="<%# Eval("ImagePath") %>" alt="<%# Eval("ImageAlt") %>" /></a><p><%# Eval("Label") %></p>Carousel with image and text (product list, spotlight, etc.)
DropDownItemText, Valueddl.DataSource = presenter.ItemList;
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
Populate DropDown controls


Once the basic Views are identified (they tend to repeat themselves from page to page in a typical public website) they can be used to populate various Sublayouts that need to have specific looks and feels.
The View doesn’t need to match one-to-one the names of the fields in the templates. They just need to represent the types of fields that need to be rendered on a page. Image Path, Image Alt, Url, Label, Title, Text, Value – what you are essentially binding to your html or ASP.Net controls.
All you have to do on each page is let the designers come up with the html templates for you and adapt the View objects in the html to render the page.
The Sublayout then, becomes very thin. And the code-behind a mere formality – nice and clean and devoid of reams of code. Here’s an example of what a typical Sublayout  code-behind looks like:


      private void Page_Load(object sender, EventArgs e)

      {

          Item item = Sitecore.Context.Item;

          if (item != null)

          {

              RelatedProductsPresenter presenter = new RelatedProductsPresenter(item);

              adapter.Adapt();

              this.repeaterCarousel.DataSource = adapter.RelatedProducts;

              this.repeaterCarousel.DataBind();

          }

      }


Simple and clean, no?

All the work happens in the Presenter object. We simply pass it the starting point (in this case the current Sitecore Item from a product page) and the business logic will take care of looking up related products to display in a Related Products Carousel.

Each layer deals with what concerns it and no layer knows about the other. Complete separation of concerns.

Independently, we can use NUnit or MSTest to run various tests to verify we are getting the data we expect and that all the fields in the View are being populated with expected data.

If any of the rules are changed, they change inside the Presenter class and the Sublayout need not be the wiser.

So where do you start, making your own MVP Framework? Yes, you can write your own. There are plenty of samples out there for MVP patterns. It isn’t very difficult to do, but it is time-consuming.

If you’re in a rush to get started, though, Ariesnet has created a Framework to accelerate your development. It includes various interfaces, Views and Presenters that were found to be the most common in the typical public website. And it is available here. In the documentation samples it will be demonstrated how to use it in many different scenarios, from Carousels, Menus, Pagination controls, Search results, and many others.