Creating a simple homepage

In this tutorial we will create a simple home page with a title and rich text field.

The home page item only contains two fields:

First we need to create the model that will represent our home page item:

using Glass.Mapper.Sc.Configuration.Attributes;

namespace Glass.Mapper.Sites.Sc.Models.Landing
    public class HomePage
        public virtual string Title { get; set; }
        public virtual string MainBody { get; set; }

You can see that this class doesn't include any special markup however one important thing to remember when writing class with Glass.Mapper is to ensure that all your fields are marked as virtual. Glass.Mapper can automatically infer what data to load for your model by using a combination of On Demand mapping and Auto-Mapping.

Now that we have our model we can turn our attention to the home page sublayout. In the code behind we place the following code:

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

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

Here you can see that we have created an instance of SitecoreContext, this gives you access to the current Sitecore context via Glass.Mapper. The second line then loads the current context item (Sitecore.Context.Item) as the HomePage class.

Finally we have the ASCX HTML, you will notice that I have used inline statements to render the data but you can use ASP.NET Web Controls if you wish.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HomePageSublayout.ascx.cs" 
    Inherits="Glass.Mapper.Sites.Sc.layouts.Site.Landing.HomePageSublayout" %>
<div class="hero-unit">
  <h1><%=Model.Title %></h1>
  <%=Model.MainBody %>

Hit F5 and load the homepage and you should see the two fields rendered to screen:

Very quickly and without any special markup we have been able to pulled data from Sitecore onto our strongly type model.