I thought I’d write a blog around a piece of interesting functionality I developed for a new blog engine that I am currently involved with.
The requirement was to take a flat list of posts and output a dynamic, magazine style layout with was broken down into multiple rows, with each row having a varying number of posts. This needed to be a random arrangement, so that each time the blog was visited, the layout would be different and make for a more interesting user experience.
This was going to be using MVC3, so the first step was to create a database table called BlogRow. This contained all of the row variations that existed within the system, the two most important columns being “ViewName” (which stored the name of the partial view instance for that particular row type) and “NumberOfPosts” (which stored the number of posts this row required to display).
When the page began rendering, you’d start with a flat list of 24 posts, retrieved in reverse chronological order from the database. Then you’d follow this process:
- Get a random BlogRow instance from the database (where NumberOfPosts for that row is higher than the remaining posts in the flat list)
- Slice the required NumberOfPosts out of the flat list (so slicing 4 would leave you with 20 in the flat list)
- Create a model for that particular partial view, consisting of a List of Post objects and the name of the partial view for that Blog Row
- This process continues until you have no posts remaining in the flat list of posts, at which post, a model which consists of a List of Lists of Posts (confusing, right?) is sent to the main View for the front of the blog
There were a couple of pieces of extra logic around this (for example, a row consisting of a single post is only used if there’s only one post left in the list at the end), but I won’t go into all of those now. The page also stored it’s layout in the user session, preventing the layout from changing constantly for a single user every time they refreshed the page.
I couldn’t find many instances of people using a dynamic number of Partial Views/Partial View Models within a single view, so it took a bit of planning to put something together, but I ended up with a pretty effective solution.