Item information and making links

In this tutorial will will look at creating a top navigation menu which will show you how to retrieve information about an item, such as its URL, as well as how we can access child items.

I have added a couple of extra items in to the Sitecore content tree, both items have a Title field:


We need to make a model that will represent the items that will appear in this menu. To do this we have the following model:

using System.Collections.Generic;

namespace Glass.Mapper.Sites.Sc.Models.Misc
{ 
    public class MenuItem
    {
        public virtual string Title { get; set; }

        public virtual string Url { get; set; }

        public virtual IEnumerable<MenuItem> Children { get; set; }
    }
}

Notice that the Children property use an enumerable of the MenuItem class, this will allow us to recursively descend the tree.

In this model we have used two special property names Url and Children, when auto-mapping Glass.Mapper will populate the Url property with the Url of the item and the Children property with the Children of the item. You can override the behaviour with configuration which you will learn about later.

Our code behind is similar to the homepage sublayout but instead of getting the current item we get the home item:

using System;
using Glass.Mapper.Sc;
using Glass.Mapper.Sites.Sc.Models.Misc;

namespace Glass.Mapper.Sites.Sc.layouts.Site.Misc
{
    public partial class TopNavigationSublayout : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var context = new SitecoreContext();
            Model = context.GetHomeItem<MenuItem>();
        }
        public MenuItem Model { get; set; }
    }
}

We can now use our model to easily render out the top navigation, notice how we can use the Url property in the links href:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TopNavigationSublayout.ascx.cs" Inherits="Glass.Mapper.Sites.Sc.layouts.Site.Misc.TopNavigationSublayout" %>
<div class="navbar">
  <div class="navbar-inner">
    <a class="brand" href="<%=Model.Url %>"><%=Model.Title %></a>
    <ul class="nav">
        <% foreach (var item in Model.Children)
           {%>
                <li><a href="<%=item.Url %>"><%=item.Title %></a></li>
          <% } %>
    </ul>
  </div>
</div>

With this added to your site you should be able to navigate to the home page and see a list of links to each of the child pages:


In this tutorial we have seen how we can get the information about an item and how we can easily traverse to the child items of a particular item.