EditFrame with Sitecore MVC and Glass.Mapper

Ever hand to deal with html which is just not compatible with the tags that glass html helpers render for you?
And in these occasions, it pretty much seems like you are going to have to say bye bye to page editor support!
EditFrame is the answer to your problems.

This is definitely not a new concept and existed in the asp.net version of sitecore libraries too.
In this post, I will demonstrate how to get this set up in your MVC site (with glass mapper).

EditFrame basically lets you make any html page editor friendly. All you need to do, is tell it which item and which field / set of fields you want to associate with the given html.

There are 2 parts to setting this up

  • Create items with the fields you want to add support for specified
  • Add the corresponding code – passing in the item which needs to be made editable, wrapped around the html which will be editable

In this example, consider a simple Product template, with a multilist field ‘Categories’


Core Items

In core database, under /sitecore/content/Applications/WebEdit/Edit Frame Buttons, add your field, making a duplicate of the /sitecore/content/Applications/WebEdit/Edit Frame Buttons/Default folder for convenience. This will bring over with it the below items.


The title and tooltip in the above screenshot will correspond to the title and tooltip of the edit frame in page editor mode when you select the editable target html.

You can then specify the fields for which you would want to add page editor support. In this example, I have mentioned only 1, but as mentioned below, you can add a pipe delimited set of multiple fields.


Another great advantage of this approach, of separating the fields from the items / templates here, is that you can create a single folder for common fields like say Background Image, Products, Featured Links etc, which might be reused over multiple templates!

So now in the code, you need to create the frame tag and pass in the path to this folder we created, along with the item which needs to be editable.

Following is the view code:

@using sc72
@using sc72.tdsmaster.sitecore.templates.User_Defined

@inherits Glass.Mapper.Sc.Web.Mvc.GlassView<Product>

<!-- START: Product Detail -->

<b>Sku:</b> @Editable(p => p.Sku)
<b>Name:</b> @Editable(p => p.Name)
@RenderImage(p => p.Image, isEditable: true)
@using (BeginEditFrame(ItemTree.Content.Applications.WebEdit.Edit_Frame_Buttons.Site.Status.ItemPath, Model.Id.ToString()))
    if (Model.Custom_Status != null)
        <span><b>Status:</b> @Model.Custom_Status.Title</span>

@using (BeginEditFrame(ItemTree.Content.Applications.WebEdit.Edit_Frame_Buttons.Site.Categories.ItemPath, Model.Id.ToString()))
    if (Model.Custom_Categories != null && Model.Custom_Categories.Any())
        <span><b>Categories:</b> </span>
        foreach (Product_Category category in Model.Custom_Categories)
            @:&nbsp;&nbsp;&nbsp;&nbsp; @category.Title


@RenderLink(p => p.Purchase_Link, isEditable: true)

<!-- END: Product Detail -->

Here’s the resultant page in pageeditor mode:


Here are examples of scenarios when this is particularly useful:

  • Background images
  • Page editor support for sitecore reference type fields (droplinks, treelists, multilists etc)
  • Iframes / Audio / Video tags
  • Rendering sitecore data to get plugins on your page
  • Newer html tags – picture tag / canvas – Or really any HTML for which glass might not have page editor support included html helper methods.

You can also configure the above to allow inserting new items in page editor mode!


Using Custom Routes in Sitecore MVC

Many a time, we come across the need to customize our urls in sitecore.
While doing this would definitely need overriding the item resolver in sitecore, additionally we use MVC routes to be able to define the route structure we need.

In our project, we found this especially useful for bucketable items and also certain special / listing pages – where we used the JS History API to account for paging / sorting filtering and the likes.

Consider the scenario of bucketable product items:


Now, we would definitely not want the product url correspond with the sitecore structure as shown above. It would be more likely that we would want the product url to perhaps embed a super category name, a category name, and may be a sku along with the product name itself. In this case, we will implement custom routes and also override the sitecore item resolver and link provide to make the circle complete.
This kind of implementation will also let you have separate presentations on every item if you wanted to, as opposed to the approach of using sitecore wildcard nodes where the presentation couldn’t be updated by the content author for individual items.

To achieve the url we want, the route would need to be defined:

public class RouteConfig
    public static void RegisterRoutes(RouteCollection routes)
         routes.MapRoute("Products", "products/{supercategory}/{category}/{productname}/{sku}");

Point to note: If you have multiple routes which are similar – in the sense that they start with the same sequence, you will want to add most specific to most generic route to your route table.

And in your global.asax.cs, you need to register the route(s) you just created:

public override void Application_Start()

Now you will need to add to the httpRequestBegin sitecore pipeline – a new itemresolver pipeline where you need to add the logic to identify the item from the route you just created above.
Basically, for any product, if you were to get the identifiers that were declared ({supercategory},{category},{productname},{sku} in this case), the code which fetches the corresponding product item from sitecore based on these identifiers, needs to be in the itemresolver code.

In this case, we will assume that the sku is a unique identifier for a product.
Note: If you are using an item name as an identifier, you will want to ensure that the item name is unique for the template you are searching for (in the location you are searching, if it is not the entire tree). It would be best to ensure that the item names are unique in this case, in the scope you will define for the item search. You could use this post, to ensure this and add a constraint to this effect: Unique item name constraint using index search in Sitecore.

namespace myassemblyname
    public class CustomItemResolver : HttpRequestProcessor
        public override void Process(HttpRequestArgs args)
            Assert.ArgumentNotNull(args, "args");
            if (Sitecore.Context.Item != null || Sitecore.Context.Database == null || args.Url.ItemPath.Length == 0) return;

            RouteBase route = RouteTable.Routes["Products"];

            if (route == null) return;

            RouteData routeData = route.GetRouteData(new HttpContextWrapper(HttpContext.Current));

            if (routeData == null) return;

            string productSku = (string)routeData.Values["sku"];

            if (string.IsNullOrWhiteSpace(productSku)) return;

            // Logic to fetch the product from sitecore / index based on the sku fetched from the url
            // you could optionally also use the other identifiers like the category / super category etc.
            Item product = ...

            if (product == null) return;

            Sitecore.Context.Item = product;

The config update here to add the above processor:

        <processor type="myassemblyname.CustomItemResolver, myassemblyname" />

In addition to this, to complete the circle here, you will also want to customize the your sitecore link provider here. This is so that the product urls when requested from the LinkManager are returned in the format you want it to, instead of the one corresponding to the sitecore folder structure (buckets in this case)

namespace myassemblyname
    public class CustomLinkProvider : LinkProvider
        public override string GetItemUrl(Item item, UrlOptions urlOptions)
            var holdUrlOptions = urlOptions;
                urlOptions.SiteResolving = Settings.Rendering.SiteResolving;

                string customUrl;

                // We want this to apply to only Products
                if (item.TemplateID.ToString() == "<Product template guid>")
                    // Code to fetch the sku / category / super category of the product given that we have the product item itself in 'item'
                    string category = ...
                    string superCategory = ...

                    if (!string.IsNullOrWhiteSpace(category) && !string.IsNullOrWhiteSpace(superCategory))
                        // NOTE, if this is being called from an asynchronous tasks, context will be null
                        // in this case, we will need to set the url by replacing the identifiers with the corresponding values in the routes
                        if (HttpContext.Current != null)
                            var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                            customUrl = urlHelper.RouteUrl("Products", new
                    urlOptions.SiteResolving = Settings.Rendering.SiteResolving;
                    return base.GetItemUrl(item, holdUrlOptions);

The linkprovider override will also need to be applied in the config:

<linkManager defaultProvider="custom">
        <add name="custom" type="myassemblyname.CustomLinkProvider, myassemblyname" addAspxExtension="false" alwaysIncludeServerUrl="false" encodeNames="true" languageEmbedding="never" languageLocation="filePath" lowercaseUrls="true" shortenUrls="true" useDisplayName="false" />

So this should allow you to use product urls like the one below throughout your site.
Note: you are defining the custom route in a single place (in the RegisterRoutes method above), so this is a clean approach as well!


In addition to the above, you might also come across random scenarios where implementing custom routes may be a great idea. If you decide to use the history api to manage interactions like sorting / paging etc, to support maintaining listing states on page refresh, you will need custom routes implemented.

An example of this scenario, would be a product listing, accessed using yourdomain.com/products.
Say you were on page 2, had sorted by descending order of product name.
And the sameple resulting url would be:


If you didnt have custom routes implemented, and refreshed the page, you would ideally land on a 404, since the route till ‘products’ corresponds to the sitecore tree, but the remaining don’t.

To get around this, you could use a route definition like:

     routes.MapRoute("ProductListing", "products/params/{*args}");

Having a separator string like ‘params’ would be advised here so that the routes don’t interfere with each other.
Also, {*args} will correspond to a variable number of arguments.
You could also fetch the entire string of these variable arguments in your controller action using the method signature:

public ActionResult CustomIndex(string args = null)
     // args will contain the string after params, in this example '2/ztoa'
     // this string could be split and used to return the page to its intended state if required!

Happy routing!